【问题标题】:Downloading a file from Angular and Spring MVC API从 Angular 和 Spring MVC API 下载文件
【发布时间】:2019-05-14 06:39:34
【问题描述】:

我正在尝试通过单击 Angular 中的按钮来下载文件。已下载但大小为 0 KB 且无法打开的文件。

这是我目前在 Angular 和 Spring MVC 中的代码

角度:

public downloadFile(fileName:string){
    console.log("ready to download");
    let param:any = {'messageId':this.loadedMessageService.messageId, 'attachmentName':fileName}
    this.http.get(`https://fakeurl.com/abc/getFile`,{params:param,responseType:'blob'}).subscribe(
      (data) => {
        let b:Blob = new Blob([data])
        //,{type: 'application/octet-stream',}
       // const fileName :string= "RL.xlsx" 
        var url = window.URL.createObjectURL(b);
        const a : HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;
       // const a = document.createElement('a');
        document.body.appendChild(a);
        a.href = url;
        a.download = fileName; 
        a.click();
        document.body.removeChild(a);
       URL.revokeObjectURL(url);
      }
    )
  }

Spring MVC:

@GetMapping(value = "/getFile")
     public @ResponseBody byte[] getFile() throws IOException {
           try {
                return messageAttachmentService.getFile(Integer.parseInt(request.getParameter("messageId")), request.getParameter("attachmentName"));
           } catch (NumberFormatException e) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                logger.error(sw.toString());
           } catch (Exception e) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                logger.error(sw.toString());
           }
           return null;
     }

现在,当我单击按钮时,文件已下载,但大小为 0 KB,并且无法打开。我之前使用类型作为应用程序/八位字节流,因为要下载的文件可以是 PDF 或文本文件或 xls。 我也提到了其他问题,并尝试将响应类型更改为 arraybuffer。那也没有解决问题。我的代码有什么问题?

【问题讨论】:

  • 如果您不使用 Angular 部分并直接从浏览器访问后端下载 URL,会发生什么情况?
  • 在这种情况下,我下载了带有“文件”扩展名的整个文件。如果我尝试使用 Acrobat Reader 打开它(因为我正在使用 pdf 进行测试),它可以正常打开。
  • 好的。在这种情况下,服务器端代码可能无关紧要。为什么要通过文件下载来使用 Angular HTTP 库/订阅方式。以老式方式访问下载链接,一切正常,不是更容易吗?
  • console.log(data) 在角度端的输出是什么?
  • 可能重复请参阅此处:stackoverflow.com/questions/35138424/…

标签: angular spring spring-mvc


【解决方案1】:

您可以尝试使用file-saver 包。它易于使用。

import * as FileSaver from 'file-saver';

const blob: any = new Blob([data], { type: 'octet/stream' });
saveAs(blob, "hello world.txt");

【讨论】:

    【解决方案2】:

    你可以这样试试。

      public downloadFile(fileName:string){
        console.log("ready to download");
        let param:any = {'messageId':this.loadedMessageService.messageId, 'attachmentName':fileName}
        this.http.get(`https://fakeurl.com/abc/getFile`,{params:param,responseType:'blob'}).subscribe(
          (data) => {
              const a = document.createElement('a');
              document.body.appendChild(a);
              const blob: any = new Blob([data], { type: 'octet/stream' });
              const url = window.URL.createObjectURL(blob);
              a.href = url;
              a.download = data.fileName;
              a.click();
              window.URL.revokeObjectURL(url);
          }
        )
      }
    

    【讨论】:

    • 如果您能说明为什么 OP 的解决方案不起作用而您的解决方案起作用,我会很好。仅仅一小段代码并不是一个好的答案,因为很难理解为什么这可以解决任何问题。
    猜你喜欢
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2019-02-08
    • 2021-03-07
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多