同源,a标签downlaod属性浏览器基本都支持下载
非同源,提供两个下载方法
function downloadFile(url, filename) { fetch(url).then(response => { return response.blob(); }).then(blob => { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = filename; a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(a.href); }).catch(error => console.error('downloading file fail:', error)); } // 使用示例 downloadFile('https://example.com/xxx.pdf', 'xxx.pdf');
function downloadFile(url, fileName) { let x = new XMLHttpRequest(); x.open("GET", url, true); x.responseType = 'blob'; x.onload = function (e) { let url = window.URL.createObjectURL(x.response) let a = document.createElement('a'); a.href = url a.download = fileName; a.click() } x.send(); }
执行报错
Access to fetch at 'http://。。。' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
解决:需要服务端设置允许跨域请求
springboot举例(以前写过,找个相似的,附上未测试的代码参考)
CorsConfig.java
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; //解决跨域访问的配置 @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { //path:“/**”表示的是拦截对应域名下的所有请求,也可以自行设置请求路径。 registry.addMapping("/**") .allowedOrigins() //allowedOrigins():设置能跨域访问我的域名,其中*号代表任意域名。 //.allowedOriginPatterns("*")//注意版本 // 是否允许携带cookie?默认情况下值为false。 .allowCredentials(true) // 接受的请求方式。 .allowedMethods("GET","POST","PUT","DELETE") // 本次许可的有效时长,单位是秒 .maxAge(3600); } }
固定写死网址测试结果,浏览器response中应该会返回允许跨域的值:Access-Control-Allow-Origin:*
IIS参考
IIS下配置跨域设置
1.设置Access-Control-Allow-Origin
2.添加“HTTP响应标头”
打开IIS,找到“HTTP响应标头”点进去,在右侧可以看到添加,然后添加如下标头即可
Access-Control-Allow-Headers:Content-Type, api_key, Authorization
Access-Control-Allow-Origin:*

le.li
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了