0

I am trying to download a docx file from server using axios. The downloaded file is larger than the original file and appears corrupt, not able to open. The issue is not with the servlet used to download because if I use the link directly in a browser it gets downloaded perfectly.

I came across this link and tried that as well but in vain. Please let me know what I might be doing wrong. Appreciate your help. Download binary file with Axios

axios({
    method: "GET",
    url: "https://example.com/apps/GetFile?file=test.docx", //
    responsetype: "blob",
    config: {
      headers: {
        'Access-Control-Allow-Origin': 'http://localhost:1337',
        'Content-Type': 'application/json'
      }
    }
  }).then(function(response) {
    const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', 'test.docx');
    document.body.appendChild(link);
    link.click();
  })
  .catch(function(error) {
    alert(error);
  });
Phil
  • 157,677
  • 23
  • 242
  • 245
Krishnan V S
  • 1,124
  • 1
  • 13
  • 31

2 Answers2

1

As pointed out by @Phil, it was due to the mistake in responseType. It should be "responseType", not "responsetype". I need to pay more attention to details :)

Krishnan V S
  • 1,124
  • 1
  • 13
  • 31
-1

Your code should be like this:

    axios({
    method: "GET",
    url: "https://example.com/apps/GetFile?file=test.docx", //
    responseType: "blob",
    config: {
        headers: {
            'Accept': 'application/pdf'
        }
    }
}).then(function(response) {
    const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', 'test.docx');
    document.body.appendChild(link);
    link.click();
})
.catch(function(error) {
    alert(error);
});

I hope that can help u!