【问题标题】:Is this proper way to download a file in Vue?这是在 Vue 中下载文件的正确方法吗?
【发布时间】: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


    【解决方案1】:

    我认为显示为空白的 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”之间的区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 2018-09-18
      • 2015-12-21
      • 1970-01-01
      相关资源
      最近更新 更多