共用方式為


XMLHttpRequest 無法在 Microsoft Edge 中正確傳送含有空白檔案元素的 FormData

警告

已淘汰、不受支援的 Internet Explorer 11 傳統型應用程式已於特定 Windows 10 版本透過 Microsoft Edge 更新永久停用。 如需詳細資訊,請參閱 Internet Explorer 11 傳統型應用程式淘汰常見問題集 (英文)。

本文提供替代方案,以解決在 Windows 10 版本 1809 的 Microsoft Edge 中,FormData無法正確傳送包含空白檔案元素的問題XMLHttpRequest

原始產品版本: Microsoft Edge、Windows 10
原始 KB 編號: 4490157

徵兆

當使用XMLHttpRequestjQuery.ajax())方法傳送時,它無法在 Windows 10 版本 1809 的 Microsoft Edge 中正確傳送包含空白檔案元素的FormData物件。

例如,您可以設定只包含一個檔案元素的檔案,以及所有其他檔案元素空白的檔案,如下列程式代碼範例所示:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-1.12.4.js"
            integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU="
            crossorigin="anonymous"></script>
    </head>
    <body>
        <form action="/AjaxUploadSample/Home/FileUpload" enctype="multipart/form-data" method="post">
            <input name="files" id="files" type="file" value=""><br>
            <input name="files" id="files" type="file" value=""><br>
            <input name="files" id="files" type="file" value=""><br>
            <button id="btn" type="button">Async Upload</button>
        </form>
        <hr>
        <p id="message" style="white-space:pre;"></p>
        <script>
            $(document).ready(function () {
                $("#btn").on("click", function () {
                    var _form = $(this).closest("form")[0];
                    $.ajax({
                        type: "post",
                        url: _form.action,
                        processData: false,
                        contentType: false,
                        data: new FormData(_form),
                        success: function (data, textStatus, jqXHR) {
                            $("#message").text(data.Message);
                        }
                    });
                });
            });
        </script>
    </body>
</html>

當您按兩下 [ 異步上傳] 時,無法正確辨識設定檔案。

原因

當 Windows 10 版本 1809 的 Microsoft Edge 中實作 FormData 發生變更時,會出現此問題。

因應措施

若要解決此問題,請在呼叫 $.ajax() 之前插入下列程式代碼,並明確略過空的項目。

// Workaround
var _data = new FormData(_form);
if (_data.entries)
{
    var data = new FormData();
    for (var p of _data)
    {
        if (p[1])
        {
            // p[1] is the value of form entry
            data.append(p[0], p[1]);
        }
    } _data = data;
}
$.ajax(
{
    type: 'post',
    url: _form.action,
    processData: false,
    contentType: false,
    data: _data,
    success: function (data, textStatus, jqXHR)
    {
        $('#message').text(data.Message);
    }
});