admin管理员组

文章数量:1300048

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:

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:

Share Improve this question edited Oct 2, 2017 at 20:10 AspiringCanadian asked Oct 2, 2017 at 20:00 AspiringCanadianAspiringCanadian 1,6757 gold badges26 silver badges44 bronze badges 2
  • 4 The file will start to download automatically if you use an a tag <a href="http :// local.linktodocx">download</a> – mrdeleon Commented Oct 2, 2017 at 20:37
  • Does this answer your question? How can I download a file using window.fetch? – ggorlen Commented May 30, 2022 at 18:33
Add a ment  | 

1 Answer 1

Reset to default 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.

本文标签: javascriptDownload a file using fetch apiStack Overflow