[英]Multipart or base64 for AJAX file uploads?
I'm writing a single page application with EmberJS and need to upload a few files. 我正在使用EmberJS编写一个单页应用程序,并且需要上传一些文件。
I wrote a special view, that wraps the file input field and extracts the first file selected. 我写了一个特殊的视图,该视图包装了文件输入字段并提取了第一个选定的文件。 This lets me bind the File
-Object to a model-attribute. 这使我可以将File
-Object绑定到模型属性。
Now I have to choose. 现在我必须选择。
I can write a special file transform, that serialises the File
-Object to base64 and simply PUT/POST this. 我可以编写一个特殊的文件转换,将File
-Object序列化为base64并简单地将其PUT / POST。
Or I can intercept the RESTAdapter
methods createRecord
and updateRecord
to check every model for File
-Objects and switch the PUT/POST requests to multipart/form-data
and send it with the help of FormData
或者,我可以截取RESTAdapter
方法createRecord
和updateRecord
来检查每个模型的File
-Objects并将PUT / POST请求切换为multipart/form-data
并在FormData
的帮助下进行发送
Does one of these directions pose significant problems? 这些指示之一是否构成重大问题?
I've had to evaluate the same concern for a Restful API I'm developing. 我必须对正在开发的Restful API进行同样的评估。 In my opinion, the most ideal method would be to just use the RESTAdapter with base64 encoded data. 在我看来,最理想的方法是仅将RESTAdapter与base64编码的数据一起使用。
That being said, I had to use the multipart/form-data method in my case, because the data transfer is 30% higher when you base64 encode the file data. 话虽如此,我必须使用multipart / form-data方法,因为在对base64编码文件数据时,数据传输要高30%。 Since my API would be have to accept large (100MB+) files, I opted to have the POST method of the API to receive multipart form data, with the file and json data being one of the POST variables. 由于我的API必须接受大文件(超过100MB),因此我选择了API的POST方法来接收多部分表单数据,其中文件和json数据是POST变量之一。
So, unless you need to upload large files like in my case, I'd recommend always sticking to the REST methods. 因此,除非您需要像我这样上载大型文件,否则我建议始终坚持使用REST方法。
Just ran into this myself, and ended up using a simple jQuery AJAX call using the FormData
object. 自己碰到了这个问题,最后使用FormData
对象使用了一个简单的jQuery AJAX调用。 My multi-select implementation (where one can drop multiple files at once) looks like this: 我的多选实现(可以一次删除多个文件)如下所示:
filesDidChange: function() {
// Get FileList
var $input = this.$('input'),
fileList = $input.get(0).files;
// Iterate files
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i],
formData = new FormData();
// Append information to FormData instance
formData.append('attachment[title]', file.name);
formData.append('attachment[file]', file);
formData.append('attachment[post_id]', this.get('post.id'));
// Send upload request
Ember.$.ajax({
method: 'POST',
url: '/attachments',
cache: false,
contentType: false,
processData: false,
data: formData,
success: makeSuccessHandler(this),
error: makeErrorHandler(this)
});
}
// Notify
this.container.lookup('util:notification').notify('Uploading file, please wait...');
// Clear FileList
$input.val(null);
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.