js:
responseType: 'blob'解决下载zip文件无法打开的问题
export function downloadFile(query) {
return request({
url: '/ai/downloadFile',
method: 'GET',
params: query,
responseType: 'blob',
headers: {
'Content-Type': 'application/json; application/octet-stream'
}
})
}
vue:
handleDownload(filePath) {
downloadFile({ filePath: filePath }).then((blob) => {
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement("a");
link.href = url;
// 设置下载文件的文件名
link.setAttribute("download", filePath.split("/").pop());
document.body.appendChild(link);
link.click();
// 下载完成后移除链接
link.parentNode.removeChild(link);
});
},
java:
/**
* 下载文件
*
* @param filePath 文件路径 /开头
* @return 结果
* @throws IOException
*/
@GetMapping("/downloadFile")
public ResponseEntity<InputStreamResource> downloadFile(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
// 如果文件不存在,返回404
return ResponseEntity.notFound().build();
}
FileInputStream fis = new FileInputStream(file);
InputStreamResource resource = new InputStreamResource(fis);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(file.length())
.body(resource);
}