1 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
最簡(jiǎn)單的方法是不使用fetch而是使用普通的鏈接元素:
<a href="/api/download" download="sample.json">Click to download</a>
在所有現(xiàn)代瀏覽器中,該download屬性將導(dǎo)致瀏覽器將鏈接響應(yīng)保存為文件。沒有fetch要求。
但是,如果您絕對(duì)需要fetch操作,那么您基本上可以在 JS 本身中執(zhí)行此操作:獲取結(jié)果,然后創(chuàng)建一個(gè)<a>,將其href屬性設(shè)置為文件 blob,并確保download設(shè)置該屬性:
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);
});
添加回答
舉報(bào)