Dan*_*son 2 iframe file-upload internet-explorer-8
我有一个只有一个表单的表单,input:file表单的目标是一个名字iframe.当用户选择文件时,它会自动将表单发布到服务器.这适用于IE10/firefox/chrome,但在IE8中,当IE8发布表单时,我的控制器方法上的File参数为null.有没有其他人遇到这个并知道任何解决方案,为什么IE8实际上不是发布文件数据?
客户端:
function createFileUploadForm()
{
var frameName = 'fileUploadFormFrame';
var fileValue;
var fileUploadCallback = function()
{
//do stuff when the server responds after receiving the file
};
var fileInputChangedCallback = function(event)
{
if(fileInput.value != fileValue)
{
fileValue = fileInput.value;
form.submit();
}
};
var iFrame = document.createElement('iframe');
iFrame.name = frameName
document.body.appendChild(iFrame);
var form = document.createElement('form');
form.action = 'a/valid/url';
form.method = 'post';
form.enctype = 'multipart/form-data';
form.target = frameName;
var fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.name = 'File';
fileInput.accept = '.spc';
fileValue = fileInput.value;
//all browsers except IE8
//add event listener to fileInput onChange event -> fileInputChangedCallback
//IE8 fix
//add event listener to fileInput onFocus event -> fileInputChangedCallback
form.appendChild(fileInput);
document.body.appendChild(form);
}
Run Code Online (Sandbox Code Playgroud)
服务器端:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase File)
{
//do stuff with File, but in IE8 File parameter is null
}
Run Code Online (Sandbox Code Playgroud)
问题是IE8需要encoding在表单上设置一个额外的属性:
var form = document.createElement('form');
form.action = 'a/valid/url';
form.method = 'post';
form.enctype = 'multipart/form-data';
form.encoding = 'multipart/form-data'; //this additional line fixes the IE8 problem I was having
form.target = frameName;
Run Code Online (Sandbox Code Playgroud)