2

我有一个表单,其中只有一个input:file,表单的目标是一个命名的iframe. 当用户选择一个文件时,它会自动将表单发布到服务器。这适用于 IE10/firefox/chrome,但在 IE8 中,当 IE8 发布表单时,我的控制器方法上的 File 参数为空。有没有其他人遇到过这个并且知道任何解决方案,为什么 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);
}

服务器端:

[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase File)
{
    //do stuff with File, but in IE8 File parameter is null
}
4

1 回答 1

5

问题是 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;
于 2013-09-17T09:55:13.873 回答