vue+axios+springboot文件下载(兼容IE10)
废话不多说,直接上代码Controller@GetMapping("/download/{file_code}")public void download(@PathVariable("file_code") String fileCode,HttpServletRequest request,HttpServletResponse resp) throws IOException...
·
废话不多说,直接上代码
Controller
@GetMapping("/download/{file_code}")
public void download(@PathVariable("file_code") String fileCode,
HttpServletRequest request,HttpServletResponse resp) throws IOException {
SysFiles model = sysFilesService.selFileByCode(fileCode);// 文件实体
FileInputStream fis = null;
try {
String fileName = model.getFileName() + "." + model.getFileSuffix();
String filePath = model.getUrl() + "/" + model.getFileCode() + "." +
model.getFileSuffix();
fis = new FileInputStream(filePath);
resp.setContentType("application/vnd.ms-excel;charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setHeader("Content-Disposition",
"attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
byte[] b = new byte[100];
int len;
while ((len = fis.read(b)) > 0) {
resp.getOutputStream().write(b, 0, len);
}
} catch (Exception e) {
LOGGER.error("文件[ {} ]下载错误", model.getFileName());
} finally {
resp.getOutputStream().flush();
resp.getOutputStream().close();
fis.close();
}
}
view page
download(code, name, suffix) {
let fileName = name + '.' + suffix;
this.$ajax.download(baseUrl + 'api/file/download/' + code,{param})// param 为额外参数
.then((res) =>{
let data = res.data;
if(!data){
return;
}
const blob = new Blob([data])
if(window.navigator.msSaveOrOpenBlob){// 兼容IE10
navigator.msSaveBlob(blob, fileName);
}else{// 其他非IE内核支持H5的浏览器
let url = window.URL.createObjectURL(blob);
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click()
})
.catch((err) =>{
this.$message.error(err + '');
})
},
axios
var download = function(url, data){
return axios({
method: 'GET',
url: url,
params: data,
responseType: 'blob',
headers: {
'My-Token': VueCookies.get('my-token')
}
});
}
按照上面的写就可以实现文件下载
有问题评论区留言吧
==== 这是Q&A分割线=========
Q:文件下载乱码或者通过响应拦截封装axios获取不到data(undefined)
A:1.确保responseType与URL同级,不要写到header里面去。2.确保是data的取值为response.request.response(不封装的前提下可以直接通过response.data获取到)
更多推荐
已为社区贡献2条内容
所有评论(0)