Springboot+vue3 文件跨域下载

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

例子

JAVA 将文件写入OutputStream

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();
    }

前端需要接收

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设置跨域

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 @ 2022-07-26 00:19  Hexrui  阅读(967)  评论(0编辑  收藏  举报
返回顶部