我们使用的是VUE+Springboot前后端分离模式开发,本地调试的时候使用nginx解决跨越问题:
1、后台文件下载接口:
@RequestMapping(value = "/downFile")
public HttpServletResponse downloadFile(HttpServletResponse response,HttpServletRequest request) {
try {
String fileName = request.getParameter("name").toString();
// 要下载的文件的全路径名
String filePath ="D:\\test\\upload\\file\\"+fileName;
File file = new File(filePath);
// 获取文件名
String filename = file.getName().toString();
//通过流把文件内容写入到客户端
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(),"ISO-8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}
2、前端(VUE)下载文件,两种方法:
第一种方法:
页面效果(样式还没调,凑合着看吧):
元素:
<div>
<h4 style="font-weight:500;height:15px;">发票附件</h4>
<template v-for="(value,index) in attachedUrls">
<a>{{value}}</a>
<v-button-search @click='download(value)' style="float:right;">下载</v-button-search>
</template>
</div>
事件:
download(name) {
window.location.href="http://127.0.0.1:8088/server/invoice/downFile?name="+name;
}
第二种方法:
页面效果:
元素:
<div>
<h4 style="font-weight:500;height:15px;">发票附件</h4><br><br>
<template v-for="(value,index) in attachedUrls">
<a :href='attUrl+value'>{{value.substring(value.indexOf('_')+1,value.length)}}</a><br>
</template>
</div>
初始化变量:
data() {
return {
attUrl:'http://127.0.0.1:8088/server/invoice/downFile?name='
};
},
3、遇到的各种坑
①http请求报413
经调查发现是我使用的nginx的问题,前后端分离项目为解决跨域我使用了nginx反向代理,nginx对上传文件的大小有限制,需要做如下修改:
不论是linux系统还是windows系统找到nginx的conf路径下的nginx.conf文件,在http{}的大括号中添加下面几行代码:
#配置请求体缓存区大小
client_max_body_size 8M;
#设置客户端请求体最大值
client_body_buffer_size 128k;
fastcgi_intercept_errors on;
如图:
保存后重启nginx,我这里是windows下的开发环境
nginx.exe -s reload
②springboot对上传文件的大小限制
报错如下:
调查报错信息发现问题所在:
原来Spring Boot工程嵌入的tomcat限制了请求的文件大小,这一点在Spring Boot的官方文档中有说明,请求中单个文件大小上限为1Mb,单次请求的文件的总数不能大于10Mb。要更改这个默认值需要在配置文件(如application.properties)中加入两个配置(不同版本的springboot这个配置的key略有差异,大家对应版本查一下,我的Spring Boot 2.0.2):
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=50MB
如图:
一番周折之后:
成功了!!!