如何用JavaScript下载文件?现有方法导致文件损坏求助
解决文件下载后损坏的问题
你的代码导致文件损坏的核心原因是设置了mode: "no-cors",这会让fetch返回不透明响应(opaque response),无法读取到实际的文件内容,转成blob后自然是损坏的。另外原代码里注释了aElement.click(),即使blob正常也不会触发下载操作。
下面给出两种可行的解决方案:
方案一:直接利用a标签下载(最简单稳妥)
不需要借助fetch,直接通过浏览器原生的download属性处理下载:
const FileDownload = (link, fileName) => { const aElement = document.createElement("a"); aElement.setAttribute("download", fileName); aElement.href = link; // 触发点击下载 aElement.click(); }; FileDownload("https://unify.eoxyslive.com/images/jobs/image_2023_01_28T09_33_42_235Z.png", "attachment.png")
只要目标服务器允许资源被跨域访问(或同域),浏览器就会直接触发下载或弹出「另存为」窗口。
方案二:正确使用fetch(需服务器支持CORS)
如果必须用fetch,要移除mode: "no-cors"配置,同时确保目标服务器开启了CORS允许你的域名访问:
const FileDownload = async (link, fileName) => { try { const res = await fetch(link, { method: "get", referrerPolicy: "no-referrer" }); if (!res.ok) throw new Error("文件请求失败"); const blob = await res.blob(); const aElement = document.createElement("a"); aElement.setAttribute("download", fileName); const href = URL.createObjectURL(blob); aElement.href = href; aElement.click(); URL.revokeObjectURL(href); } catch (err) { console.error("下载出错:", err); } }; FileDownload("https://unify.eoxyslive.com/images/jobs/image_2023_01_28T09_33_42_235Z.png", "attachment.png")
移除no-cors后,fetch才能获取到正常的响应内容,转成有效的blob文件供下载。
内容的提问来源于stack exchange,提问作者Ajay Kumar
相关产品推荐
相关产品推荐

