[英]Is this proper way to download a file in Vue?
我只想問,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 是:
我認為顯示空白的 pdf 與您的 axios 通話有關。 您將要至少添加一個響應類型。
downloadFile:(fileId)=>instance.get('/download?fileId=' + fileId, { responseType: 'arraybuffer' })
.then(response=>{return response;})
我傳遞給 axios 的第二個 object 是一個配置 object。 在此處查看他們的文檔。
這是我用來幫助我解決類似問題的另一個 Stack Overflow。 這是另一個關於“arraybuffer”和“blob”之間的區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.