使用适用于 IE9 的 ajax 发送文件/文件上传 [英] Sending files /file upload using ajax which works in IE9
问题描述
我需要使用 IE9 支持的 ajax 上传文件.我正在使用 此处 中提到的 FormData.我的代码如下所示:
var files = new FormData();JQuery.each($('#file')[0].files, function (i, file) {files.append('文件', 文件);});$.ajax({类型:POST",网址:'/网址',缓存:假,内容类型:假,过程数据:假,数据:文件,...});
这在 Safari 和 Firefox 中工作正常,但在 IE9 中失败,因为 IE9 不支持 FormData.我尝试通过设置将其作为文件发送:
数据:$('#file')[0].files[0]contentType: 'multipart/form-data'
这会失败,因为数据是以 url 编码的形式发送的,并且无法在 java 端解析.任何有关如何解决此问题的帮助或指示将不胜感激.我需要一些适用于所有浏览器的东西.
我不需要任何上传进度条,因为文件通常很小.我不需要上传多个文件.我只需要上传一个文件.
很遗憾,您不能使用 Ajax(换句话说,XMLHttpRequest
)发送文件,但您可以使用 <iframe/>
带有 <form method="post" enctype="multipart/form-data"/>
包含 <input 类型="file"/>
使用自然"方式发送用户选择的文件.您可以使用javascript调用form.submit()
,然后从父文档中轮询以检查文件上传过程是否完成.>
jQuery
有 很多完成这项工作的酷插件,有我最喜欢的插件,例如.
I need to upload files using ajax which has to be supported in IE9. I was using FormData as mentioned here. My code looks like this:
var files = new FormData();
JQuery.each($('#file')[0].files, function (i, file) {
files.append('file', file);
});
$.ajax({
type: "POST",
url: '/url',
cache: false,
contentType: false,
processData: false,
data: files,
...
});
This works fine in Safari and Firefox, but fails in IE9 as the FormData is not supported in IE9. I tried sending just as a file by setting:
data: $('#file')[0].files[0]
contentType: 'multipart/form-data'
This fails as the data is sent in url-encoded form and is cannot be parsed at the java side. Any help or pointer on how to solve this will be greatly appreciated. I need something that works across all browsers.
EDIT: I do not need any upload progress bar as the files are usually small. I do not need to upload multiple files. I just need a single file upload.
Unfortunately you cannot use Ajax (XMLHttpRequest
in other words) for sending files, but you can implement a similar behavior using the <iframe/>
with a <form method="post" enctype="multipart/form-data"/>
that contains an <input type="file"/>
which sends a user chosen file using the "natural" way. You can use javascript to call the form.submit()
then poll that <iframe/>
from parent document to check whether the file upload process is done.
jQuery
has a lot of cool plugins for getting this job done, there is my favorite one, for example.
这篇关于使用适用于 IE9 的 ajax 发送文件/文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!