【发布时间】:2021-05-15 14:57:18
【问题描述】:
我只是想问一下,Vue中下载文件的好方法是什么?
因为当我这样做时,它不起作用,文件是空的,并且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 是:
【问题讨论】:
标签: javascript vue.js http download axios