1,前端页面
<el-button type="primary" @click="downloadHandle()">下载模板</el-button>
2,调用js
downloadHandle () {
this.$http({
url: this.$http.adornUrl('/custom/publicfile/upload'),
method: 'get',
params: this.$http.adornParams({
'fileName': '审计台账模板'
}),
responseType: 'blob'
}).then((res) => { // 处理返回的文件流
let blob = new Blob([res.data])
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, '审计台账模板.xlsx')
} else {
let elink = document.createElement('a')
elink.download = '审计台账模板.xlsx'
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
document.body.removeChild(elink)
}
}).catch(err => {
console.warn(err)
})
},
3,controller写法
@RequestMapping("/upload")
public void upload(HttpServletResponse response, @RequestParam String fileName) {
// 业务需要,根据名称查询到文件在fastdfs服务器的地址
PublicFileVO publicFileVO = publicFileBussiness.getByName(fileName);
FastDFSClient.download(response, publicFileVO.getPfPath());
}4,工具类
/**
* 文件下载
* @param response
* @param filePath
*/
public static void download(HttpServletResponse response, String filePath){
ServletOutputStream out;
BufferedInputStream buf;
try {
//filePath: http://192.8.8.88:8888/group1/M00/00/03/CtUBGF2cJYaAEekLAAA5N2ybXw469.xlsx
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + filePath.substring(filePath.lastIndexOf("/") + 1));
URL url = new URL(filePath);
//使用输入读取缓冲流读取一个文件输入流
buf=new BufferedInputStream(url.openStream());
//利用response获取一个字节流输出对象
out=response.getOutputStream();
//定义个数组,由于读取缓冲流中的内容
byte[] buffer=new byte[1024];
int n;
//while循环一直读取缓冲流中的内容到输出的对象中
while((n = buf.read(buffer))!= -1) {
out.write(buffer, 0, n);
}
//写出到请求的地方
out.flush();
buf.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}如有问题,请多指出,谢谢
版权声明:本文为m0_37906846原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。