[javascript]使用ajax下載檔案

有關網頁及相關語法的討論
回覆文章
頭像
tim
文章: 1379
註冊時間: 2008年 11月 26日, 00:49

[javascript]使用ajax下載檔案

文章 tim »

雖然實務上不需要使用 ajax 下載檔案, 只需要使用動態 form post 的方式, 讓目前的 url 移轉至 download url 即可由 server-side 回傳下載檔案的 response header, 不過若是真的想使用 ajax 方式進行檔案下載, 可以參考這篇:

在處理 ajax 下載檔案時, 可以參考這篇的資料:
http://stackoverflow.com/questions/1608 ... -ajax-post

代碼: 選擇全部

$.ajax({
    type: "POST",
    url: url,
    data: params,
    success: function(response, status, xhr) {
        // check for a filename
        var filename = "";
        var disposition = xhr.getResponseHeader('Content-Disposition');
        if (disposition && disposition.indexOf('attachment') !== -1) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
        }

        var type = xhr.getResponseHeader('Content-Type');
        var blob = new Blob([response], { type: type });

        if (typeof window.navigator.msSaveBlob !== 'undefined') {
            // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
            window.navigator.msSaveBlob(blob, filename);
        } else {
            var URL = window.URL || window.webkitURL;
            var downloadUrl = URL.createObjectURL(blob);

            if (filename) {
                // use HTML5 a[download] attribute to specify filename
                var a = document.createElement("a");
                // safari doesn't support this yet
                if (typeof a.download === 'undefined') {
                    window.location = downloadUrl;
                } else {
                    a.href = downloadUrl;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                }
            } else {
                window.location = downloadUrl;
            }

            setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
        }
    }
});
多多留言, 整理文章, 把經驗累積下來.....
回覆文章