如何在不使用多部分的情况下使用AJAX上传文件? [英] How can I upload a file using AJAX without using multipart?

查看:57
本文介绍了如何在不使用多部分的情况下使用AJAX上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序允许用户上传的唯一文件是图像,并且它们始终作为表单中的唯一输入字段上载.因此,不需要多部分,而无需多部分解析器,我可以更轻松地使用文件.

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.

如何在不使用AJAX和Vanilla Javascript进行多部分处理的情况下上传文件?此外,它通常应支持所有浏览器的最新版本.

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

推荐答案

您可以简单地通过XHR级别2发送关联的File或Blob本身.例如,我在上传库中维护(

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).

您可能已经知道,要在MPE POST请求中发送文件,您必须将文件添加到FormData对象并通过XHR2发送,或者提交包含文件输入的表单.如果要在非MPE POST请求中上传文件,只需执行以下操作:

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

当然,这只能在支持File API的浏览器中完成.另外,如果您希望将任何参数与文件一起发送,则必须将它们包含在查询字符串中.

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.

这篇关于如何在不使用多部分的情况下使用AJAX上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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