
[英]How to download a result of a fileInput element as a file for any kind of file type?
[英]How to download files in javascript, It can be any type of file
我从后端获取文件链接,我需要直接下载文件或在单击保存按钮时询问 savsAs。
这是一个文件的链接。
https://unify.eoxyslive.com/images/jobs/image_2023_01_28T09_33_42_235Z.png
我已经尝试过这种方法来下载文件及其下载但它已损坏。 并没有打开。
const FileDownload = (link, fileName) => { fetch(link, { method: "get", mode: "no-cors", referrerPolicy: "no-referrer" }).then((res) => res.blob()).then((res) => { const aElement = document.createElement("a"); aElement.setAttribute("download", fileName); const href = URL.createObjectURL(res); console.log(href); aElement.href = href; aElement.setAttribute("target", "_blank"); // aElement.click(); URL.revokeObjectURL(href); }); }; FileDownload("https://unify.eoxyslive.com/images/jobs/image_2023_01_28T09_33_42_235Z.png", "attachment.png")
触发下载的最简单方法是下载链接,无 JavaScript。
<a href="file.ext" download>
(该属性也可以与一个值一起使用,以建议一个不同于 href 的文件名)
但这只能执行没有额外标头的简单 GET 请求。
一旦您需要标头(用于身份验证等),您将不得不使用fetch
并创建一个下载链接(而不是像您的示例中那样带有target=_blank
的链接;它有效但在功能和语义上不如download
)一个 Blob URL。
尽管需要标头(或除 GET 之外的其他方法),但要使下载链接正常工作的解决方法是让 Service Worker 透明地处理额外的标头。
此外,如果您对服务器有任何控制权,请让它发送Content-Disposition: attachement
响应 header。这将鼓励浏览器触发下载,即使是普通链接也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.