SpringBoot+Vue实现文件下载

本文介绍了如何在SpringBoot和Vue应用中实现文件下载,重点解决了跨域问题和文件内容乱码的问题。首先,通过修改Vue前端的HTTP请求方法从GET变为POST来解决跨域问题。其次,调整后台控制器的返回类型以正确返回文件内容,避免出现undefined。最后,针对文件下载时出现的乱码问题,通过设置responseType为'arraybuffer'并调整返回内容类型为excel的正确格式,成功实现了文件的正常下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、前台vue代码,没有使用axios,用的是this.$http.post来实现的

this.$http({
     url: this.$http.adornUrl('/stats/importExportUsers/downloadTemplate'),
     method: 'post',
     responseType: 'arraybuffer'
 }).then((res) => {
     let url = window.URL.createObjectURL(new Blob([res.data]))
     let a = document.createElement('a')
     a.setAttribute("download","userTemplate.xls")
     a.href = url
     a.click();
  })

2、后台代码使用的是springBoot的一个controller

// 导入模板下载路径,在application.yml文件中配置的路径
@Value("${capitek.usertemplate.path}")
private String templatePath;  

@PostMapping("/downloadTemplate")
public void downloadTemplate(HttpServletRequest request, HttpServletResponse response){  
    	File file = new File(templatePath);
    	byte[] buffer = new byte[1024];
    	BufferedInputStream bis = null;
    	OutputStream os = null; //输出流
    	try {
    	   //判断文件父目录是否存在
	       if (file.exists()) {
	          //设置返回文件信息
	           response.setContentType("application/vnd.ms-excel;charset=UTF-8");
	           response.setCharacterEncoding("UTF-8");
	           response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode("userTemplate.xls","UTF-8"));	           
               os = response.getOutputStream();
               bis = new BufferedInputStream(new FileInputStream(file));
               while(bis.read(buffer) != -1){
                   os.write(buffer);
               }
	       }
        } catch (Exception e) {
            e.printStackTrace();       
        } finally {
        	try {
        		if(bis != null) {
        			bis.close();
        		}
        		if(os != null) {
        			os.flush();
        			os.close();
        		}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

 

遇到的问题:

1、开始的时候跳转不到后台代码中,提示跨域问题,于是设置返回值等多种方式,无果。发现使用的请求是this.$http.get请求,修改给post之后,成功跳转到后台代码中。

错误信息:Access to XMLHttpRequest at 'http://localhost:8082/stats/importExportUsers/downloadTemplate' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

2、执行完代码之后返回到前台内容为undefined,一度认为是输出流读取的有问题,后发现后台方法中添加了返回值,是公司封装的工具,所有返回成功时,内容为undefined,改为void之后,可以看到返回了内容。

3、返回内容之后,在vue页面进行了处理,但是下载的文件中是一堆乱码,经过查询是未设置返回类型,因为使用的是bolb所以设置了{responseType: 'blob'},仍然无效果。

      然后查询到时字节流的话需要按照字节方式设置返回值类型,修改为responseType: 'arraybuffer'之后,成功下载。

 

response.setContentType中的内容

application/vnd.ms-excel:可以保存为xls格式的excel文件(兼容老版本)

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:则会保存为xlsx

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值