DIV CSS 佈局教程網

ajaxfileupload.js 上傳報錯的兩種成因與解法
編輯:關於JavaScript     

檔案上傳是日常開發中很常見的功能。ajaxFileUpload 這個老外掛至今仍有專案在用,但它有兩個高頻報錯,以下分別說明成因與修法。

基本用法回顧

$.ajaxFileUpload({
    url: 'www.coding/mobi/file/uploadSingleFile.html',  // 處理上傳的後端
    secureuri: false,
    fileElementId: 'image2',       // file 控件的 id,即 <input type="file" id="image2">
    dataType: 'json',
    success: function (data, status) {
        console.log(data);
    },
    error: function (data, status, e) {
        alert(e);
    }
});

問題一:回傳的 JSON 被 pre 標籤包住

照範例寫法通常能跑,但一直會跳錯誤。原因不在你的設定,而在外掛的 uploadHttpData 方法——它用 eval 解析回應,而某些後端環境會把 JSON 包在 <pre> 標籤裡,eval 自然失敗。

原始碼最後一段長這樣:

uploadHttpData: function (r, type) {
    var data = !type;
    data = type == "xml" || data ? r.responseXML : r.responseText;

    if (type == "script") jQuery.globalEval(data);
    if (type == "json") eval("data = " + data);
    if (type == "html") jQuery("<div>").html(data).evalScripts();

    return data;
}

把它改成先剝掉 pre 標籤,再改用 $.parseJSON:

uploadHttpData: function (r, type) {
    var data = !type;
    data = type == "xml" || data ? r.responseXML : r.responseText;

    if (type == "script") jQuery.globalEval(data);

    if (type == "json") {
        // JSON 被 <pre> 標籤包住時會出錯,先用正則取出內容
        // update by hzy
        var reg = /<pre.+?>(.+)<\/pre>/g;
        var result = data.match(reg);
        result = RegExp.$1;
        // update end
        data = $.parseJSON(result);
        // eval("data = " + data);
    }

    if (type == "html") jQuery("<div>").html(data).evalScripts();

    return data;
}

關鍵有兩點:正則中的 + 之後要加 ? 使其非貪婪,否則多行 JSON 會匹配過頭;以及用 $.parseJSON 取代 eval,避免執行任意程式碼的風險。

問題二:jQuery.handleError is not a function

這個錯誤來自版本差異:handleError 是 jQuery 1.4.2 之前才有的內部方法,之後被移除。而 ajaxFileUpload 的範例多半搭配 jQuery 1.2,一旦你換成新版 jQuery 就會爆這個錯。

解法是把缺的方法補回 ajaxfileupload.js 中:

handleError: function (s, xhr, status, e) {
    // 若有本地回呼則呼叫
    if (s.error) {
        s.error.call(s.context || s, xhr, status, e);
    }
    // 觸發全域回呼
    if (s.global) {
        (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
    }
}

更根本的建議

ajaxFileUpload 的本質是「利用 hidden iframe 模擬 Ajax」,所以才有 responseText 被包標籤、需要 eval 這類歷史包袱。今天若要處理檔案上傳,直接用 FormData 搭配 $.ajax 或 fetch 即可,不必再依賴 iframe hack:

var fd = new FormData();
fd.append('Filedata', $('#image2')[0].files[0]);

fetch('/mobi/file/uploadSingleFile.html', { method: 'POST', body: fd })
    .then(function (r) { return r.json(); })
    .then(function (data) { console.log(data); })
    .catch(function (err) { console.error(err); });

進度條可以用 XMLHttpRequest.upload.onprogress 取得,這是 iframe 方案完全做不到的。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved