[JavaScript] 使用 Fetch API 來下載檔案(Download File)

Banner

一般來說檔案要讓使用者下載很簡單,只需要在畫面上放一個超連結導向到檔案的路徑,當使用者點擊即開始下載。
然而並不是每次都那麼簡單,也是有可能會有需要藉由 API 的方式來產生並下載檔案的情況,此時只好自己寫 JavaScript 去呼叫 API 並下載檔案。

範例程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Download file
fetch('Your api or file url', {
method: 'GET',
// 其他設定或是需要傳遞的資料
})
.then((response) => response.blob())
.then((blob) => {
var url = window.URL.createObjectURL(blob); // create url from blob
var fileLink = document.createElement('a'); // create link for file
fileLink.href = url;
fileLink.download = 'output.csv'; // download filename
document.body.appendChild(fileLink); // append file link to download
fileLink.click();
fileLink.remove(); // remove file link after click
})
.catch((error) => {
// Handle error here.
});

其主要概念就是取得檔案 Blob 並轉換成 URL,最後藉由 HTML 的超連結標籤(<a>)來模擬下載檔案。

參考資料