简体   繁体   English

如何在不使用 multipart 的情况下使用 AJAX 上传文件?

[英]How can I upload a file using AJAX without using multipart?

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.因此, multipart 是不必要的,而且我可以更轻松地使用文件而无需 multipart 解析器。

How can upload a file without using multipart using AJAX and vanilla Javascript?如何使用 AJAX 和 vanilla Javascript 在不使用 multipart 的情况下上传文件? Also, it should generally support the latest version of all browsers.此外,它通常应该支持所有浏览器的最新版本。

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).您可以简单地通过 XHR 级别 2 发送关联的文件或 Blob 本身。例如,在我维护的上传库 ( Fine Uploader ) 中,您可以选择在多部分编码的 POST 请求(所有浏览器)或非 MPE 请求(仅限支持文件 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.要在 MPE POST 请求中发送文件,您可能已经知道,您必须将文件添加到 FormData 对象并通过 XHR2 发送,或者提交包含文件输入的表单。 If you want to upload a file in a non MPE POST request, simply do this:如果要在非 MPE POST 请求中上传文件,只需执行以下操作:

xhr.send(file);

Of course, this can only be done in browsers that support the File API.当然,这只能在支持 File API 的浏览器中完成。 Also, if you want to send any parameters along with your file, you will have to include them in the query string.此外,如果您想随文件一起发送任何参数,则必须将它们包含在查询字符串中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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