这是在 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 是:

enter image description here

解决方法

我认为显示空白的 pdf 与您的 axios 调用有关。您至少要添加一个响应类型。

downloadFile:(fileId)=>instance.get('/download?fileId=' + fileId,{ responseType: 'arraybuffer' })
  .then(response=>{return response;})

我在这里传递给 axios 的第二个对象是一个配置对象。查看他们的文档 here

Here's 另一个我用来帮助我解决类似问题的 Stack Overflow。 here's 另一个关于“arraybuffer”和“blob”之间的区别。