前言
在做需求過程中我們大概率會遇到在瀏覽器中下載文件的需求,如果僅僅是這個要求的話很簡單,但是平常下載方式都會存在一個問題,就是 pdf 文件會直接在瀏覽器中打開而不是直接下載。
解決方案
這種需求的解決方式就是將PDF文件的 MIME type 改為 application/octet-stream
並加入 Content-Disposition:attachment
header,原本的 pdf 文件 MIME type 為 application/pdf
,瀏覽器識別到這個 type 之后會自動在瀏覽器打開,所以說我們在這里修改 type 即可。(前后台都可以,我們本次采用前台)
代碼如下:
//下載文件的鏈接 var url="xxxxx"; fetch(url, { method: 'get', responseType: 'arraybuffer', }) .then(function (res) { if (res.status !== 200) { return res.json() } return res.arrayBuffer() }) .then((blobRes) => { // 生成 Blob 對象,設置 type 等信息 const e = new Blob([blobRes], { type: 'application/octet-stream', 'Content-Disposition':'attachment' }) // 將 Blob 對象轉為 url const link = window.URL.createObjectURL(e) handleFileDownload(link, filename) }).catch(err => { console.error(err) })