1 回答

TA貢獻1830條經驗 獲得超9個贊
最簡單的方法是不使用fetch而是使用普通的鏈接元素:
<a href="/api/download" download="sample.json">Click to download</a>
在所有現代瀏覽器中,該download屬性將導致瀏覽器將鏈接響應保存為文件。沒有fetch要求。
但是,如果您絕對需要fetch操作,那么您基本上可以在 JS 本身中執行此操作:獲取結果,然后創建一個<a>,將其href屬性設置為文件 blob,并確保download設置該屬性:
fetch(...)
.then(res => res.blob())
.then(blob => {
const blobURL = URL.createObjectURL(blob);
// create our <a> to force a download for the response
const dl = document.createElement(`a`);
dl.href = blobURL;
dl.download = `sample.json`;
// In order for the link to "trigger" we need to add it to the document.
// If we don't, dl.click() won't do anything. So add it, click it, then remove it.
dl.style.display = `none`;
document.body.appendChild(dl);
dl.click();
document.body.removeChild(dl);
});
添加回答
舉報