前端vue从后端springboot下载指定文件
前端接口:
downloadTemplate(){
return request({
url: '/api/v1/weekprofit/downloadtemplate',
method: 'post',
responseType: 'blob'
})
}
vue代码:
downloadTemplate() {
weeklyProfitAPI.downloadTemplate().then( res => {
const data = res.data;
let url = window.URL.createObjectURL(new Blob([data]));
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', '文件名');
document.body.appendChild(link);
link.click();
});
},
后端代码:
@PostMapping(value = "/downloadtemplate")
public void downloadFile(HttpServletResponse response,HttpServletRequest request) {
String path = "路径";
String fileName = "文件名";
String filePath = path + "\\" + fileName;
File file = new File(filePath);
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader(
"Content-disposition",
"attachment; filename="+fileName);
try(
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
// 输出流
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
){
byte[] buff = new byte[1024];
int len = 0;
while ((len = bis.read(buff)) > 0) {
bos.write(buff, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}