有時候你可以需要透過使用 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