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

青春壹個敷衍的年華 提交于 2020-01-24 01:14:29

问题


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?


回答1:


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
});


来源:https://stackoverflow.com/questions/18083496/how-to-encode-a-file-from-the-file-system-as-multipart-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!