How can I upload a file using AJAX without using multipart?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-30 08:35:25

问题


The only file my app allows users to upload are images, and they are always uploaded as the sole input field in a form. Thus, multipart is unnecessary, and I could much more easily consume the file without a multipart parser.

How can upload a file without using multipart using AJAX and vanilla Javascript? Also, it should generally support the latest version of all browsers.


回答1:


You can simply send the associated File or Blob itself via XHR level 2. For example, in the upload library I maintain (Fine Uploader) you can elect to have files sent in multipart encoded POST requests (all browsers) or non MPE requests (only browsers that support the File API).

To send the file in a MPE POST request, as you may already know, you must either add your file to a FormData object and send that via XHR2, or submit a form containing a file input. If you want to upload a file in a non MPE POST request, simply do this:

xhr.send(file);

Of course, this can only be done in browsers that support the File API. Also, if you want to send any parameters along with your file, you will have to include them in the query string.



来源:https://stackoverflow.com/questions/16605263/how-can-i-upload-a-file-using-ajax-without-using-multipart

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