一、Vue部分
methods:{
download() {
axios({
url: 'http://10.57.20.90:8083/dealer/download',
method: 'GET',
responseType: 'blob', // 重要:指定响应类型为 blob
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', '经销商导入模板.xlsx'); // 设置下载文件名
document.body.appendChild(link);
link.click(); // 触发下载
document.body.removeChild(link); // 下载后移除链接
window.URL.revokeObjectURL(url); // 释放内存
})
.catch((error) => {
console.error('下载失败', error);
});
},
}
二、Springboot部分。(使用类路径的方式获取文件路径,在打jar包上传服务器后,避免了找不到文件的问题,该代码是jdk1.8的实现方法)
注意:文件需要放在resources文件夹的类路径下。文件路径是打包完成后的文件所在的路径。如图:
下图为打包后的路径:
@GetMapping("download")
public ResponseEntity<ByteArrayResource> download() {
try (InputStream inputStream = getClass().getResourceAsStream("/com/szc/suppliermanagement/file/经销商模板.xlsx");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
if (inputStream == null) {
return new ResponseEntity<>(HttpStatus.GONE);
}
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] bytes = outputStream.toByteArray();
ByteArrayResource resource = new ByteArrayResource(bytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=经销商模板.xlsx");
return ResponseEntity.ok()
.headers(headers)
.body(resource);
} catch (IOException e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}