使用 Axios 下载二进制文件 [英] Download binary file with Axios

查看:44
本文介绍了使用 Axios 下载二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如下载PDF文件:

axios.get('/file.pdf', {
      responseType: 'arraybuffer',
      headers: {
        'Accept': 'application/pdf'
      }
}).then(response => {
    const blob = new Blob([response.data], {
      type: 'application/pdf',
    });
    FileSaver.saveAs(blob, 'file.pdf');
});

下载文件的竞争为:

[object Object]

这里有什么问题?为什么二进制数据没有保存到文件中?

What is wrong here? Why binary data not saving to file?

推荐答案

我能够创建一个可行的要点(不使用 FileSaver)如下:

I was able to create a workable gist (without using FileSaver) as below:

axios.get("http://my-server:8080/reports/my-sample-report/",
        {
            responseType: 'arraybuffer',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/pdf'
            }
        })
        .then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'file.pdf'); //or any other extension
            document.body.appendChild(link);
            link.click();
        })
        .catch((error) => console.log(error));

希望有帮助.

干杯!

这篇关于使用 Axios 下载二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆