Reputation: 738
I just want to ask, what is a good way to download file in Vue?
Because when I do it like this, it is not working, files are empty, and there is a problem with content-disposable, I dont't know if I can be sure that format is correct:
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);
})
When this solution below is working, and it works perfectly, it downloads good file, with good content, format (formats can be different, pdf, png, txt etc.) and with good name but I don't think it goes through axios interceptors, so I don't think it is secured etc. (maybe im wrong)
downloadFile(fileId) {
console.log(fileId);
let link = document.createElement('a');
link.href = "http://localhost:8081/download?fileId=" + fileId;
link.click();
}
My axios method looks like this:
downloadFile:(fileId)=>instance.get('/download?fileId=' + fileId).then(response=>{
return response;
})
Can somebody tell me how to do it in a good way with blob, content-disposable and secure solution?
My method on backend looks like this:
@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);
}
And response of this link: http://localhost:8081/download?fileId=xyz is:
Upvotes: 0
Views: 3731
Reputation: 33
I think the pdf showing up blank has to do with your axios call. You're going to want to add at least a response type.
downloadFile:(fileId)=>instance.get('/download?fileId=' + fileId, { responseType: 'arraybuffer' })
.then(response=>{return response;})
The second object I'm passing to axios here is a config object. See their docs here.
Here's another Stack Overflow that I used to help me with a similar issue. And here's another about the difference between 'arraybuffer' and 'blob'.
Upvotes: 2