javascript 使用 fetch api 下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46532861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download a file using fetch api
提问by AspiringCanadian
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 docxis downloaded.
我试图通过单击一个按钮来下载文件,但它不下载文件。虽然,如果我转到浏览器上的 url,则会下载docx。
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:
回复:
回答by Balázs édes
A fetchcall either resolves with a Responseobject or rejects with an error. If you want the response body (which in your case is probably a binary blob) then you could try:
一个fetch呼叫或者解决了与一个Response物体或次品,并显示错误。如果您想要响应正文(在您的情况下可能是二进制 blob),那么您可以尝试:
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.
您仍然需要注意显示它,将它写入磁盘,无论您想用它做什么。


