vue3.0+springboot 下载文件后,在本地运行没有问题,可以打开,但是部署到服务器上之后,下载成功后,提示文件打不开,如下图
这是哪里的问题
你的路径E: 是写死了Windows路径,Linux系统不支持,你可以先用相对路径试试。
这篇文章:SpringBoot+VUE实现文件下载功能 也许能够解决你的问题,你可以看下后台接口如下
@RequestMapping("/download")
public void download(@RequestBody FileVO fileVO, HttpServletResponse response){
File file = new File("E:"+fileVO.getPath());
byte[] buffer = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
//文件是否存在
if (file.exists()) {
//设置响应
response.setContentType("application/octet-stream;charset=UTF-8");
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.addHeader("Content-Length",String.valueOf(file.length()));
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();
}
}
}
前端vue如下:
downloadFile(list).then(res => {
let url = window.URL.createObjectURL(new Blob([res.data],{type:"application/vnd.ms-excel;charset=utf-8"}))
let a = document.createElement('a')
a.setAttribute("download","默认地址.xlsx")
a.href = url
a.click();
}).catch(err => console.log(err))