IE8 post file targeting iframe, arrives on server as null

天涯浪子 提交于 2019-12-24 05:22:06

问题


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:


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;


来源:https://stackoverflow.com/questions/18789983/ie8-post-file-targeting-iframe-arrives-on-server-as-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!