Download image using Axios in React?

Viewed 7772

I'm trying to download an image using a GET request in Axios, and then download this to the users PC. I need to use Axios as the get request has an Authorization header.

Below I have my function to download the image and store it as a blob:

return axios({
  method: 'GET',
  headers: { Authorization: `Bearer ${jwt}` },
  url: `https://example.com/api/${url}`,
  responseType: 'blob'
})
.then(response => {
  if (response) {
    const file = new Blob([response.data], {type:'image/png'})
    return file
  }
  return Promise.reject('An unknown error occurred');
});

I then user FileSaver to save this:

  const image = await userService.downloadImage(slug, this.props.token);
  FileSaver.saveAs(image, "image.png")

What I am getting though is an error when downloading the file saying

"Failed - Network Error"

If I look in the developer option of Chrome, I can see the GET request to the API, and in the preview tab, I can see the image.

Any suggestions as to where I am going wrong?

1 Answers

This means axios works fine, however, file-saver does not do the Download.

Looking into readme of file-saver repo, you could see the supported browsers:

enter image description here

Thus, try to upgrade the current browser or test with another browser. Also, make sure the size of the image does not exceed sizes mentioned in the matrix above.

You can check the size by adding console.log(file.size)

.then(response => {
  if (response) {
    const file = new Blob([response.data], {type:'image/png'})
    console.log(file.size) // !!! this line
    return file
  }
Related