(共556篇)
全部分类

使用axios下载java流文件的两种方式
[ Ajax ] 

方式一

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
async function download(){
    const res = await axios.get(url, {
        responseType:'blob'
    })
    const blob = new Blob([res.data], {
      type: res.data.type,
    });

    const link = document.createElement('a');
    const file = URL.createObjectURL(blob);
    const fileName = new Date().getTime() + '.xls';
    link.href = file;
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
}

方式二

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
async function download(){
    const res = await axios.get(url, {
        responseType:'blob'
    })

    const blob = new Blob([res.data]);
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = function (e) {
        const fileName = `${+new Date()}.xls`;
        const link = document.createElement('a');
        link.href = e.target.result;
        link.download = fileName;
        link.click();
    };
}

使用axios请求返回文件流形式的接口时,记得带上responseType:'blob'参数,

注意: 这个参数是属于请求参数, 不属于headers参数!