问题
我的 pdf 下载代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
export const downloadPDF = (data) => { axios({ method: data.method || "POST", url: isCompleteURL(data.url) ? data.url : appConfig.baseURL + data.url, data: data.params, params: data.params, responseType: "blob", }).then((res) => { const _res = res.data; let blob = new Blob([_res], { type: "application/pdf" }); let downloadElement = document.createElement("a"); let href = window.URL.createObjectURL(blob); downloadElement.href = href; downloadElement.style.display = "none"; downloadElement.download = data.fileName; document.body.appendChild(downloadElement); downloadElement.click();
document.body.removeChild(downloadElement); window.URL.revokeObjectURL(href); }); };
|
在 PC 端没啥问题,但是发现在 iPhone 设备 Safari 上会报错:
未能完成操作。(WebKitBlobResource 错误”)
解决方案
如果以编程方式将 a 标签注入 DOM,要确保不要过早移除它。可以 1s 后将其删除:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
export const downloadPDF = (data) => { axios({ method: data.method || "POST", url: isCompleteURL(data.url) ? data.url : appConfig.baseURL + data.url, data: data.params, params: data.params, responseType: "blob", }).then((res) => { const _res = res.data; let blob = new Blob([_res], { type: "application/pdf" }); let downloadElement = document.createElement("a"); let href = window.URL.createObjectURL(blob); downloadElement.href = href; downloadElement.style.display = "none"; downloadElement.download = data.fileName; document.body.appendChild(downloadElement); downloadElement.click();
setTimeout(() => { document.body.removeChild(downloadElement); window.URL.revokeObjectURL(href); }, 1000); }); };
|