fetch请求文件流并下载(Excel)

1、blob文件流

fetch(url,{
    method: 'get',
    responseType: 'blob'
}).then(res => {     
    return res.blob();
}).then(blob => {
    let bl = new Blob([blob], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    let fileName = '文件名'+".xlsx";
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
})

2、arraybuffer文件流

把上面的blob改成arraybuffer就好了

fetch(url,{
    method: 'get',
    responseType: 'arraybuffer'
}).then(res => {     
    return res. arraybuffer();
}).then(arraybuffer => {
    let bl = new Blob([arraybuffer], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    let fileName = '文件名'+".xlsx";
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
})
青云直上三千码
原文地址:https://www.cnblogs.com/djjlovedjj/p/14671925.html