jQuery 使用适用于 IE9 的 ajax 发送文件/文件上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13483408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending files /file upload using ajax which works in IE9
提问by Alice
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:
我需要使用必须在 IE9 中支持的 ajax 上传文件。我正在使用这里提到的 FormData 。我的代码如下所示:
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:
这在 Safari 和 Firefox 中工作正常,但在 IE9 中失败,因为 IE9 不支持 FormData。我尝试通过设置作为文件发送:
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.
这将失败,因为数据以 url 编码形式发送,并且无法在 java 端解析。任何有关如何解决此问题的帮助或指示将不胜感激。我需要一些适用于所有浏览器的东西。
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.
编辑:我不需要任何上传进度条,因为文件通常很小。我不需要上传多个文件。我只需要一个文件上传。
回答by Dan K.K.
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.
不幸的是,您不能使用 Ajax(XMLHttpRequest
换句话说)来发送文件,但是您可以使用包含使用“自然”方式发送用户选择的文件的<iframe/>
with来实现类似的行为。您可以使用 javascript 调用来自父文档的then poll来检查文件上传过程是否完成。<form method="post" enctype="multipart/form-data"/>
<input type="file"/>
form.submit()
<iframe/>
jQuery
has a lot of cool pluginsfor getting this job done, there is my favorite one, for example.