在Windows 8.1中使用BackgroundUploader进行多部分/相关上载

时间:2014-10-11 18:54:59

标签: windows-runtime windows-8.1 windows-phone-8.1 multipart background-transfer

我想在Windows 8.1中通过 BackgroundUploader 使用 Multipart / related Content-Type上传文件

我的代码如下

BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Content-Type", "multipart/related; boundary=foo_bar_baz");
uploader.Method = "POST";

// Create upload content
List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();

// File metadata
var part = new BackgroundTransferContentPart();
part.SetHeader("Content-Type", "text/plain");
part.SetText(file.DisplayName);
parts.Add(part);

// File
// Here file is of type StorageFile
part = new BackgroundTransferContentPart();
part.SetHeader("Content-Type", file.ContentType);
part.SetFile(file);
parts.Add(part);

UploadOperation upload = await uploader.CreateUploadAsync(new Uri("upload_url",UriKind.Absolute), parts);

await upload.StartAsync().AsTask(cts.token);  // cts is CancellationTokenSource

然而,当我运行此代码时,我得到一个例外

  

WinRT信息:'boundary':如果设置了'Content-Type'标题,   边界不能为空,必须与中的边界相匹配   'Content-Type'标题。

我的代码中有什么错误/缺失?

2 个答案:

答案 0 :(得分:1)

如果您使用带有四个参数的CreateUploadAsync,则以下内容可能会有所帮助:

var uploader = new BackgroundUploader();
uploader.SetRequestHeader("Content-Type", "multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY-3770FB3C-534D-4E6B-9BE0-392FDA960F7B");

var upload = await uploader.CreateUploadAsync(uri, parts, "form-data", "0xKhTmLbOuNdArY-3770FB3C-534D-4E6B-9BE0-392FDA960F7B");

await upload.StartAsync();

在“SetRequestHeader”中设置边界而不使用“”(引号)。 稍后设置与CreateUploadAsync的最后一个参数相同的边界。

答案 1 :(得分:0)

如果要传递内容部件列表,则无需设置Conent-Type标头。它是自动设置的。

但是,如果您坚持这样做,请尝试:

uploader.SetRequestHeader(
    "Content-Type", 
    "multipart/form-data; boundary=\"foo_bar_baz\"");

<强>更新

尝试使用带有四个参数的CreateUploadAsync重载,其中第四个参数是边界。见这里:http://msdn.microsoft.com/en-us/library/ie/hh923975