Springboot+vue3 文件跨域下载

后台返回流,前端需要接收,否则图片不能下载。

例子

JAVA 将文件写入OutputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void download(String filePath, HttpServletResponse resp) throws IOException {
        File file = new File(localPath + filePath);
        String fileName = file.getName();
        InputStream inputStream = new FileInputStream(file);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inputStream.close();
        byte[] data = outStream.toByteArray();
        resp.setContentType(FileUtils.getContentType(FileUtils.getExtName(fileName)));
        // 设置返回文件名
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        OutputStream os = resp.getOutputStream();
        os.write(data);
        os.flush();
        os.close();
    }

前端需要接收

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const onDownloadImg = async () => {
  const res = await downloadImg()
  readFileToDownload(res)
}
 
 * 读取文件并下载
 * @param {*} response
 */
function readFileToDownload(response) {
  const blob = new Blob([response.data])
  const a = document.createElement('a')
  const href = window.URL.createObjectURL(blob) // 下载链接
  a.href = href
  a.download = decodeURI(response.headers['content-disposition'].split(';')[1].split('=')[1]) // 获取后台设置的文件名称
  // a.download = new Date().getTime() + '.xlsx'
  document.body.appendChild(a)
  a.click() // 点击下载
  document.body.removeChild(a) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}

nginx设置跨域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
map $http_origin $allow_origin {
    default "";
    "~^(https?://localhost(:[0-9]+)?)" $1;
    "~^(https?://127.0.0.1(:[0-9]+)?)" $1;
    "~^(https?://([\w]+.)?[\w]+.pseal.vip)" $1;  #允许一级和二级域名
}
 
server {
    listen       80;
    server_name  api.pseal.vip;
    #access_log   "D:/Develop/UPUPW_ANK_W64/Logs/N_logs/api.pseal.vip_proxy.log"  main;
    vhost_traffic_status off;
    location / {
        add_header Access-Control-Allow-Origin $allow_origin;
        add_header Access-Control-Allow-Headers 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With';
        add_header Access-Control-Allow-Methods 'GET,POST,OPTIONS';
        add_header Access-Control-Allow-Credentials 'true';
        # 允许客户端Js读到Content-Disposition 用于文件下载读取文件名
        add_header Access-Control-Expose-Headers 'Content-Disposition';
        if ($request_method = 'OPTIONS') {
            return 204;
        }
        proxy_pass http://localhost:8072;
        include uproxy.conf;
    }
}

 

posted @   Hexrui  阅读(992)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
返回顶部
点击右上角即可分享
微信分享提示