在 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中文网其他相关文章!