简体   繁体   中英

How to encode a file from the file system as multipart/form-data?

I want to let users upload photos to Facebook in my image viewer app. As seen in this post, Facebook Graph API - upload photo using JavaScript , I have to encode my photos as multipart/form-data to be able to upload them. How to archive this encoding on Windows.Storage.StorageFile items?

You need to open that photo (of type Windows.Storage.StorageFile ) for reading, convert it's stream to blob, append it to FormData object and upload using whatever Ajax library you want ( WinJS.xhr , jQuery.ajax etc).

Following code illustrates it better than words:

file.openReadAsync().done(function(fileStream) {                
   var fileData = MSApp.createBlobFromRandomAccessStream(file.contentType, fileStream);
   var formData = new FormData();
   formData.append('upload', fileData, file.name);

   ... // send formData as xhr request body
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM