在AJAX Post 回應中處理檔案下載
設計AJAX 應用程式時,通常會處理各種回應類型,包括JSON 和潛在回應類型的文件附件。根據 Content-Type 和 Content-Disposition 標頭偵測回應類型非常簡單。然而,觸發下載對話框可能會帶來挑戰。
幸運的是,現代瀏覽器透過 FileAPI 提供了解決方案。以下程式碼片段示範如何在AJAX post 請求中實現檔案下載:
// Using native XMLHttpRequest var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.responseType = 'blob'; xhr.onload = function () { if (this.status === 200) { // Retrieve the blob and filename from the response var blob = this.response; var filename = ""; var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition && disposition.indexOf('attachment') !== -1) { filenameRegex = /filename[^;=\n]*=((['"])).*?|[^;\n]*)/; matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, ''); } // Manage file download based on browser capabilities if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE workaround for a known issue window.navigator.msSaveBlob(blob, filename); } else { var URL = window.URL || window.webkitURL; var downloadUrl = URL.createObjectURL(blob); var a = document.createElement("a"); if (a.download !== 'undefined') { a.href = downloadUrl; a.download = filename; document.body.appendChild(a); a.click(); } else { window.location.href = downloadUrl; } setTimeout(function() { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup } } }; xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send($.param(params, true));
如果使用jQuery.ajax:
$.ajax({ type: "POST", url: url, data: params, xhrFields: { responseType: 'blob' // to avoid binary data being mangled on charset conversion }, success: function(blob, status, xhr) { // Retrieve the blob and filename from the response var filename = ""; var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition && disposition.indexOf('attachment') !== -1) { filenameRegex = /filename[^;=\n]*=((['"])).*?|[^;\n]*)/; matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, ''); } // Manage file download based on browser capabilities if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE workaround for a known issue window.navigator.msSaveBlob(blob, filename); } else { var URL = window.URL || window.webkitURL; var downloadUrl = URL.createObjectURL(blob); var a = document.createElement("a"); if (a.download !== 'undefined') { a.href = downloadUrl; a.download = filename; document.body.appendChild(a); a.click(); } else { window.location.href = downloadUrl; } setTimeout(function() { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup } } });
透過結合這些技術,您可以確保您的AJAX post 請求可以無縫處理文件附件並觸發客戶端的下載對話方塊。
以上是如何在 AJAX Post 回應中觸發文件下載?的詳細內容。更多資訊請關注PHP中文網其他相關文章!