繁体   English   中英

使用 Axios 下载二进制文件

[英]Download binary file with 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]

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

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

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));

希望它有帮助。

干杯!

我能够根据 Nayab Siddiqui 的回答下载一个 tgz 文件。

const fsPromises = require('fs').promises;
const axios = require('axios'); 

await axios.get('http://myServer/myFile.tgz',
        {
            responseType: 'arraybuffer', // Important
            headers: {
                'Content-Type': 'application/gzip'
            }
        })
        .then(async response => {
            await fsPromises.writeFile(__dirname + '/myFile.tgz', response.data, { encoding: 'binary' });
        })
        .catch(error => {
            console.log({ error });
        });

看起来 response.data 只是一个普通对象。 Blob 接受它们的第一个参数“一个由 ArrayBuffer、ArrayBufferView、Blob 或 DOMString 对象组成的数组”。

尝试将其包装在 JSON.stringify 中

const blob = new Blob([JSON.stringify(response.data)]

那么它将满足 DOMString 要求。

这种方法可能对将来寻找答案的人有所帮助。

var axios = require("axios");
const fs = require("fs");

var config = {
  method: "get",
  url: YOUR_REQUEST_URL,
  responseType: "arraybuffer",
  headers: {
   //put your headers here if any required
  },
};

axios(config)
  .then(function (response) {
    fs.writeFileSync("/path/to/file", Buffer.from(response.data));
  })
  .catch(function (error) {
    console.log(error);
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM