IE8/9中的FormData

20

我已经实现了这个使用Ajax上传文件的脚本,在其他浏览器中运行得非常完美,但在IE浏览器中不起作用。我注意到formData在IE9及以下版本不受支持,是否有在IE中替代formData的方法?我想使用纯JavaScript。

    function doObjUploadExplorer(url, lnk_id, file, progress, success, content, frm, div_dlg, start_func){
    var file_input = null,
      frm_data = new FormData(),
      req;

    try {
        //firefox, chrome, safari etc
        req = new XMLHttpRequest();
    }

    catch (e) {
        // Internet Explorer Browsers
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }


if (document.getElementById(file)) {
    file_input = document.getElementById(file);

    for (var i = 0; i < file_input.files.length; ++i) {
        frm_data.append(file, file_input.files[i]);
    }
}

req.upload.addEventListener('progress', function(e) {  //Event called while upload is in progress
    if (progress !== undefined
            && e.lengthComputable) {
        $('#' + progress).html('<font>Uploading... ' + Math.round((e.loaded / e.total) * 100) + '%</font>');
    }
});

req.upload.addEventListener('load', function(e) {  //Event called when upload is completed
    $('#' + progress).html('<font>Retrieving updated data...</font>');
});

req.upload.addEventListener('error', function(e) {  //Event called when an error is returned by the server
    alert('An error has occurred...');
});

req.addEventListener('readystatechange', function(e) {        
    if (this.readyState === 4) {
        if (this.status === 200) {
            if (content !== undefined) {
                $('#' + content).html(this.response);
            }

            if (success !== undefined) {
                showChkMark(success);
            }
        } else {
            console.log('Server replied with HTTP status: ' + this.status);
        }


        if (progress !== undefined) {
            $('#' + progress).hide();
        }

        if (div_dlg !== undefined) {
            $('#' + div_dlg).dialog('close');
        }

        $('#' + file)
        .attr('disabled', false)
        .val('');
    }
});

if (progress !== undefined) {
    $('#' + progress).show();
}

$('#' + file).attr('disabled', true);
url += (
        url.indexOf('?') === -1
        ? '?'
        : '&'
    );
url += 'lnk_id=' + lnk_id + '&file=' + file;
req.open('POST', url);
req.setRequestHeader('Cache-Control', 'no-cache');

if (start_func !== undefined) {
    start_func.apply();
    setTimeout(function() {
        req.send(frm_data);
    }, 500);
} else {
    req.send(frm_data);
}}

我认为没有其他选择。 - Arun P Johny
请查看类似的帖子,这个问题实际上没有什么解决办法。https://dev59.com/52sz5IYBdhLWcg3wcXTF - Liam Newmarch
我曾经遇到过与files[0]和FormData相关的类似问题。这个解决方案对我很有效。 (https://dev59.com/xYPba4cB1Zd3GeqP0P8N) - SJ03
1个回答

19

FormData在IE浏览器中仅支持IE10及以上版本,经过一些研究,我认为最好的解决方案是使用ajaxForm:http://malsup.com/jquery/form/ ,该解决方案在IE8/9中完美运行,对于IE7则不确定。


你用了哪个更好的插件呢? - Alex B
3
你的链接与任何ajaxForm无关,而是涉及到jquery-upload-progress - ProfK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接