【问题标题】:How to download file in angular from java's response?如何从java的响应中以角度下载文件?
【发布时间】:2021-01-04 20:18:13
【问题描述】:

我在后端有带有 spring boot 的 angular 7 应用程序,我将文件保存在资源文件夹中,并且下载它们时遇到了麻烦。 这是我的控制器:

@RequestMapping(value = "/getfile", method = RequestMethod.POST)
    public void getFile(@RequestBody long id, HttpServletResponse response) {
        try {
            FileExpense fileExpense = fileExpenseRepo.findById(id).orElseThrow(() -> new CustomException(String.format("Договор (id:%s) не найден", id)));
                    if(fileExpense != null) {
                        File fileDownload = new File(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
                        response.setHeader("Content-Dispasition", "attachment; filename=" + fileExpense.getFileName());
                        response.setContentType("application/vnd.ms-excel");

                        OutputStream outputStream = response.getOutputStream();

                        Path path = Paths.get(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
                        byte[] data = Files.readAllBytes(path);
                        outputStream.write(data);
                        outputStream.flush();
                    }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
        }
    }

和角度服务:

public getFile(id: number): Observable<any> {
    return this.http.post('/expense/getfile', id);
  }

以及组件中的下载功能:

downloadFile(fileJson: FileExpenseJson){
    this.expenseService.getFile(fileJson.id).subscribe(data => {
      let blob = new Blob([data.blob], {type: 'application/vnd.ms-excel'});
      let url = window.URL.createObjectURL(blob);
      let filename = fileJson.fileName;
      if (navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        let a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
      window.URL.revokeObjectURL(url);
    });
  }

这给了我错误:消息:“位置 0 处 JSON 中的意外标记 P” 请帮忙 。无论如何,谢谢)

【问题讨论】:

标签: angular typescript


【解决方案1】:

我找到了一个解决方案:问题是我没有从前端发送带有 response-type : 'blob' 的选项。它向我发送默认 json ,而不是 blob

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2020-07-30
    • 2015-10-16
    • 2019-06-21
    • 2020-12-05
    相关资源
    最近更新 更多