2

I am trying to download a file by clicking on a button it doesn't download the file. Although, if I go to the url on my browser then the docx is downloaded.

Fetch request:

const response = await fetch(`/template/${id}/docx`, {
  method: 'GET',
  credentials: 'include',
});

const blob = await response.blob();

const file = new File([blob], id, {type: blob.type, lastModified: Date.now()});

Response:

enter image description here

AspiringCanadian
  • 1,595
  • 6
  • 24
  • 43
  • 4
    The file will start to download automatically if you use an a tag download – mrdeleon Oct 02 '17 at 20:37
  • Does this answer your question? [How can I download a file using window.fetch?](https://stackoverflow.com/questions/32545632/how-can-i-download-a-file-using-window-fetch) – ggorlen May 30 '22 at 18:33

1 Answers1

4

A fetch call either resolves with a Response object or rejects with an error. If you want the response body (which in your case is probably a binary blob) then you could try:

const response = await fetch(`/template/${id}/docx`, {
  method: 'GET',
  credentials: 'include',
});
const doc = await response.blob()

You would still have to take care of displaying it, writing it on the disk, whatever you want to do with it.

Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
  • How do I go about converting it into docx? Is there no way to download the file directly without having to go through blob conversion? – AspiringCanadian Oct 02 '17 at 20:08
  • 1
    What do you mean downloading it? Do you want to display the standard file download dialog on some event, and let the user download the file? In that case you could just do something like this: https://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery – Balázs Édes Oct 02 '17 at 20:11
  • @AnAspiringCanadian saw the update, not really sure about your intent. If you are in the browser, you don't have access to the users file system from js, so if you just want to do stuff with the file in memory then you have your answer. – Balázs Édes Oct 02 '17 at 20:16
  • That post helped. I added the path over a hidden anchor tag and triggered a click because we already have the docx files saved and there isnt a need to convert blob to docx. – AspiringCanadian Oct 02 '17 at 20:50