有時候你可以需要透過使用 Ajax 的方法來下載檔案,例如使用 `bearer token` 時,所以現代的瀏覽器可以使用以下的方法達成。

### 使用 Axios

在這年代,在使用 Ajax 的大概都是在使用 Axios,這次筆者也是使用 Axios 來達成。 

```js
// use axios
Axios({
	
	// target url
	url: 'http://yourdomain/getfile'
	
	// get method
	method: 'GET',
	
	// remote response type, use 'blob' or 'arraybuffer'
	responseType: 'arraybuffer'

}).then(r => {
	
	// create object url
	const url = window.URL.createObjectURL(new Blob([r.data]));
	
	// create link to object
	const link = document.createElement('a');
	
	// set link to object
	link.href = url;
	
	// set download file name
	link.setAttribute('download', 'download.zip');
	
	// launch download
	link.click();
	
	// delete object when download finished
	window.URL.revokeObjectURL(url);
});
```

在上面 `responseType` 可以使用 `blob` 來處理圖片資料,筆者自己親身測試過用 `arraybuffer` 來處理 `zip` 檔案是可以的,但是用 `blob` 來處理 `zip` 檔案就不行了。 

以下這條 Thread 有討論過這個問題,筆者也是在當中整合出來 :

https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)