IE8 post file targeting iframe, arrives on server

2019-07-17 09:35发布

I have a form with just an input:file in it and the form targets a named iframe. when the user selects a file it automatically posts the form to the server. This works in IE10/firefox/chrome, but in IE8 the File parameter on my controller method is null when IE8 posts the form. Has anyone else encountered this and know of any solutions, why isn't IE8 actually posting the file data?

ClientSide:

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);
}

ServerSide:

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

1条回答
迷人小祖宗
2楼-- · 2019-07-17 09:52

the problem was that IE8 requires an additional encoding property on the form to be set:

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;
查看更多
登录 后发表回答