49

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?

Anton Pelykh
  • 2,274
  • 1
  • 18
  • 21

4 Answers4

124

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));
starball
  • 20,030
  • 7
  • 43
  • 238
Nayab Siddiqui
  • 1,971
  • 1
  • 15
  • 18
5

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

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);
  });
Aayush Neupane
  • 1,066
  • 1
  • 12
  • 29
-3

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.

proto_khal
  • 67
  • 1
  • 7