从Angular和Spring MVC API下载文件

时间:2019-05-14 06:39:34

标签: angular spring spring-mvc

我试图通过单击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,并且无法打开。之前我将type用作application / octet-stream,因为要下载的文件可以是PDF或文本文件或xls。 我也提到了其他问题,并尝试将响应类型更改为arraybuffer。那也没有解决问题。我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

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

import * as FileSaver from 'file-saver';

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

答案 1 :(得分:0)

您可以尝试这样。

  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);
      }
    )
  }