最近在做一個文件下載的功能,這里把做的過程中用的技術和坑簡要總結下。
1. 單文件下載(a標簽)
同源單文件
針對單文件的情況下,同源的文件,可以通過 < a> 標簽的 download 屬性下載文件
const elt = document.createElement('a'); elt.setAttribute('href', url); elt.setAttribute('download', 'file.png'); elt.style.display = 'none'; document.body.appendChild(elt); elt.click(); document.body.removeChild(elt);但是這個方案并不適用于非同源的資源,此時它相當于普通的超鏈接,點擊會跳轉到資源頁面,而不是下載。
非同源圖片
如果不存在CORS問題, 可以借助Blob實現下載(構造xhr請求文件地址, 以Blob的形式接收Response):
function downloadWithBlob(url) { fetch(url).then(res => res.blob().then(blob => { var a = document.createElement('a'); var url = window.URL.createObjectURL(blob); var filename = 'file.png'; a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); }));}如果存在CORS問題,可以考慮使用 canvas 將圖片轉換成 base64 編碼之后再通過 標簽的 download 屬性下載
function downloadPic(url) { const img = new Image; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); img.onload = function() { canvas.width = this.width; canvas.height = this.height; ctx.drawImage(this, 0, 0); const elt = document.createElement('a'); elt.setAttribute('href', canvas.toDataURL('image/png')); elt.setAttribute('download', 'file.png'); elt.style.display = 'none'; document.body.appendChild(elt); elt.click(); document.body.removeChild(elt); }; img.crossOrigin = 'anonymous'; img.src = url;}2. 單文件下載(iframe)
iframe方式是在頁面內隱藏iframe, 然后將下載地址加載到iframe中, 從而觸發瀏覽器的下載行為
const iframe = document.createElement('iframe'); iframe.src = url; iframe.style.display = 'none'; document.body.appendChild(iframe);但是這里發現,即使是同域的圖片,也無法完成下載,這是為啥呢?
這里就有個上面的a鏈接下載沒有提到的問題:什么樣的鏈接才能觸發瀏覽器的下載:
url如何觸發瀏覽器自動下載
一個url能否觸發瀏覽器自動下載,主要看該請求響應頭response header是否滿足,一般是看Content-Disposition和Content-Type這兩個消息頭:
response header中指定了Content-Disposition為attachment,它表示讓瀏覽器把消息體以附件的形式下載并保存到本地 (一般還會指定filename, 下載的文件名默認就是filename) response header中指定了Content-Type 為 application/octet-stream(無類型) 或 application/zip(zip包時)等等。(其中 application/octet-stream表示http response為二進制流(沒指定明確的type), 用在未知的應用程序文件,瀏覽器一般不會自動執行或詢問執行。瀏覽器會像對待 設置了HTTP頭Content-Disposition 值為 attachment 的文件一樣來對待這類文件)新聞熱點
疑難解答
圖片精選