Search code examples
windows-runtimewindows-8.1windows-phone-8.1multipartbackground-transfer

Multipart/related upload using BackgroundUploader in Windows 8.1


I want to upload a file using Multipart/related Content-Type via BackgroundUploader in windows 8.1

My code is as follows

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

However, when I run this code I get an Exception saying

WinRT information: 'boundary': If the 'Content-Type' header is set, the boundary cannot be empty and must match the boundary set in the 'Content-Type' header.

What is wrong/missing in my code?


Solution

  • If you are passing a list of content parts, you don't need to set the Conent-Type header. It's set automatically.

    However if you insist in doing so, try:

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

    UPDATE:

    Try using the CreateUploadAsync overload that takes four parameters, where the fourth parameter is the boundary. See here: http://msdn.microsoft.com/en-us/library/ie/hh923975