有没有办法在Internet Explorer中实现以下解决方案?(IE7及以上版本)
链接: 使用jQuery.ajax发送multipart/formdata
这个解决方案的代码在其他浏览器上运行良好,但在IE浏览器上存在问题。
有没有办法在Internet Explorer中实现以下解决方案?(IE7及以上版本)
链接: 使用jQuery.ajax发送multipart/formdata
这个解决方案的代码在其他浏览器上运行良好,但在IE浏览器上存在问题。
我也曾经遇到过这个问题,对于需要的人可能会有用。 FormData只支持IE10及以上版本,这里是链接。在旧浏览器中无法像现代浏览器一样使用FormData绑定输入字段,因此会出现错误。在IE中无法通过AJAX上传文件。有两种替代方法可供选择:
以下是代码
if(!isAjaxUploadSupported()){ //IE fallfack
var iframe = document.createElement("<iframe name='upload_iframe_myFile' id='upload_iframe_myFile'>");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("src","javascript:false;");
iframe.style.display = "none";
var form = document.createElement("form");
form.setAttribute("target", "upload_iframe_myFile");
form.setAttribute("action", "fileupload.aspx"); //change page to post
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");
form.style.display = "block";
var files = document.getElementById("myFile");//Upload Id
form.appendChild(files);
$conv("#container_myFile").html("Uploading...");
document.body.appendChild(form);
document.body.appendChild(iframe);
iframeIdmyFile = document.getElementById("upload_iframe_myFile");
// Add event...
var eventHandlermyFile = function () {
if (iframeIdmyFile.detachEvent)
iframeIdmyFile.detachEvent("onload", eventHandlermyFile);
else
iframeIdmyFile.removeEventListener("load", eventHandlermyFile, false);
response = getIframeContentJSON(iframeIdmyFile);
}
if (iframeIdmyFile.addEventListener)
iframeIdmyFile.addEventListener("load", eventHandlermyFile, true);
if (iframeIdmyFile.attachEvent)
iframeIdmyFile.attachEvent("onload", eventHandlermyFile);
form.submit();
return;
}
////var data = new FormData();
//// code go here(for modern browsers)
function isAjaxUploadSupported(){
var input = document.createElement("input");
input.type = "file";
return (
"multiple" in input &&
typeof File != "undefined" &&
typeof FormData != "undefined" &&
typeof (new XMLHttpRequest()).upload != "undefined" );
}
function getIframeContentJSON(iframe){
//IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases
try {
// iframe.contentWindow.document - for IE<7
var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
response;
var innerHTML = doc.body.innerHTML;
//plain text response may be wrapped in <pre> tag
if (innerHTML.slice(0, 5).toLowerCase() == "<pre>" && innerHTML.slice(-6).toLowerCase() == "</pre>") {
innerHTML = doc.body.firstChild.firstChild.nodeValue;
}
response = eval("(" + innerHTML + ")");
} catch(err){
response = {success: false};
}
return response;
}
或者尝试寻找现成的jQuery上传插件。$( "#yourformid" ) .attr( "enctype", "multipart/form-data" ) .attr( "encoding", "multipart/form-data" );
FormData
不支持 IE < 10。仅适用于 IE10+。 - Paul Vargas