同源,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:*
   

 

posted on 2024-05-07 22:49  le.li  阅读(25)  评论(0编辑  收藏  举报