一般分為兩種情況:1呀页、后端返回blob數(shù)據(jù)流妈拌。2、后端返回base64字節(jié)
1蓬蝶、blob數(shù)據(jù)流
可以直接用a標(biāo)簽?zāi)M點擊事件直接下載
const fileName = 'test.jpg';
const blob = new Blob([xxx]);
const blobUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = fileName;
a.click();
//釋放之前通過調(diào)用URL.createObjectURL()創(chuàng)建的對象
window.URL.revokeObjectURL(blobUrl);
備注:由于 Blob
接口的生命周期問題及潛在的內(nèi)存泄漏風(fēng)險,此方法在 Service Worker 中不*可用猜惋。
2丸氛、base64字節(jié)
//1、采用atob的方法函數(shù)會對經(jīng)過 Base64編碼的字符串進行解碼
atob(encodedData)
//1著摔、先base64轉(zhuǎn)成blob流
new Blob([res],{
type: "application/json",
})
//2缓窜、模擬a標(biāo)簽點擊事件下載