问题描述
因为我这样做的时候,不行,文件为空,content-disposable有问题,不知道能不能确定格式正确:
api.downloadFile(fileId).then(response => {
let blob = new Blob([response.data],{ type: response.headers['content-type'] });
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "nameofFile" + '.pdf';
link.click();
}).catch(error=>{
console.log(error);
})
当下面的这个解决方案工作并且完美运行时,它会下载好的文件,内容、格式(格式可以不同,pdf、png、txt 等)和好的名称,但我不认为它通过 axios 拦截器,所以我不认为它是安全的等(也许我错了)
downloadFile(fileId) {
console.log(fileId);
let link = document.createElement('a');
link.href = "http://localhost:8081/download?fileId=" + fileId;
link.click();
}
我的 axios 方法是这样的:
downloadFile:(fileId)=>instance.get('/download?fileId=' + fileId).then(response=>{
return response;
})
有人能告诉我如何使用 blob、内容一次性和安全的解决方案以好的方式做到这一点吗?
我的后端方法如下:
@GetMapping(value = "/download")
public ResponseEntity<Resource> download(@AuthenticationPrincipal User user,@RequestParam("fileId") String fileId) throws FileNotFoundException {
Document file = storingService.loadFileByUsernameAndFileId(user.getUsername(),fileId);
Resource resource = new ByteArrayResource(file.getBinary().getData());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_disPOSITION,"attachment; filename=\"" + file.getFileName() + "\"")
.header(HttpHeaders.CONTENT_TYPE,file.getContentType())
.body(resource);
}
此链接的响应:http://localhost:8081/download?fileId=xyz 是: