AspiringCanadian
AspiringCanadian

Reputation: 1665

Download a file using fetch api

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

Upvotes: 2

Views: 26272

Answers (1)

Balázs Édes
Balázs Édes

Reputation: 13807

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.

Upvotes: 4

Related Questions