@GetMapping("/downloadFile")
public ResponseEntity downloadFile(@RequestParam String fileName) throws IOException {
Resource resource = fileService.loadFileAsResource(fileName);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
其中,loadFileAsResource()方法需要返回一个实现了 Spring 的Resource接口的文件资源对象。
downloadFile(fileName: string): void {
this.fileService.downloadFile(fileName).subscribe(data => {
let blob = new Blob([data], { type: 'application/octet-stream' });
// 使用 createObjectURL 将响应数据转换为 URL
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
});
}
其中,downloadFile()方法需要返回一个Observable对象,将响应数据以二进制数据流的形式传递给subscribe()响应函数。
通过以上两步操作,应该可以解决Angular前端Spring后端文件下载不起作用或损坏的问题。