简体   繁体   中英

Download binary file with Axios

For example, downloading of PDF file:

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

The contend of downloaded file is:

[object Object]

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

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

Hope it helps.

Cheers !

I was able to download a tgz file based on Nayab Siddiqui answer.

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

It looks like response.data is just a regular object. Blobs take in their first argument "an Array of ArrayBuffer, ArrayBufferView, Blob, or DOMString objects."

Try wrapping it in JSON.stringify

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

Then it will satisfy the DOMString requirement.

This approach might be helpful to someone looking for answer in the future.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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