没有jQuery的javascript xhr文件上传 [英] javascript xhr file upload without jQuery

查看:72
本文介绍了没有jQuery的javascript xhr文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在不使用jquery的情况下上传xhr文件. (请不要说使用jQuery).

i have some trouble to make xhr file upload without jquery. (please don't said that use jQuery).

如果浏览器支持FormData API并使用它,我听说也可以上传文件.

if the browser support FormData API and use it, i heard it is possible to upload file(s) also.

问题是我不知道如何将附件添加到FormData对象中.第二个问题是如何通过XHR发送FormData?我的意思是,看下面的代码:

the matter is i don't know how the attach file into FormData object. and second problem is how to send the FormData via XHR? i mean, look at the code below:

var formData = new FormData();
formData.append('somevalue', 'somevalue'); // string
formData.append( ???, ??? ); // file

var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Content-type', 'multipart/form-data; charset=UTF-8');

xhr.open('post', 'URL TO UPLOAD', true);
xhr.onreadystatechange = function() { ... };

xhr.send( ?? WHAT SHOULD BE HERE IF THE FORM DATA CONTAINS FILE? JUST FORM DATA ?? );

请查看代码,尤其是第二个"formData.append部分".我不知道如何将FILE DATA附加到formData对象中.

please look at the code, especially second "formData.append part". i don't know how to append FILE DATA into formData object.

第二,如果我想通过XHR发送"formData",是否要将"formData"变量放入这样的"xhr.send"方法中?

and second, if i want to send "formData" via XHR, do i just put "formData" variable into "xhr.send" method like this?

xhr.send(formData);

或者,我应该做些更多的事情吗?很难在Google上找到信息,因此如果有人知道此问题,非常感谢您告诉我或建议我下一步该怎么做.谢谢!

or, should i do something more? it is hard to find the information on google so if someone know about this problem, it will be very appreciated to tell me or advice me how should i do next. thanks!

推荐答案

formData.append( ???, ??? ); // file

是的,一个文件. MDN文档中有一个示例:

Yes, a file. There is an example in the MDN documentation:

formData.append('userpic', myFileInput.files[0], 'chris.jpg');

xhr.setRequestHeader('Content-type', 'multipart/form-data; charset=UTF-8');

删除. XHR将为您生成正确的内容类型.手动执行此操作将无法包含(必要的)边界信息.

Remove that. XHR will generate the correct content type for you. Doing it manually will fail to include the (essential) boundary information.

第二,如果我想通过XHR发送"formData",是否要将"formData"变量放入这样的"xhr.send"方法中?

and second, if i want to send "formData" via XHR, do i just put "formData" variable into "xhr.send" method like this?

是的

这篇关于没有jQuery的javascript xhr文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆