Download file sent in response angular2

后端 未结 1 1940
一生所求
一生所求 2020-12-11 14:25

I know it is a dumb question but can someone tell me how can I prompt the user to download a file that is sent by the backend in the response?

相关标签:
1条回答
  • 2020-12-11 14:36

    You have two possibilities:

    1. If the backend sends the file directly to the browser by clicking a link then the backend should use the content type application/octet-stream in the headers. That causes the browser to ask the user how to save/open the file.

    2. If you load the file from the backend through Angular code (Http Module) then you could use filesaver.js or a similar library. Then you have the full control and can prompt the user yourself.

      npm install file-saver --save
      

      ... and the typings:

      npm install @types/file-saver --save-dev
      

      The code in the service:

      public getFile(path: string):Observable<Blob>{
        let options = new RequestOptions({responseType: ResponseContentType.Blob});
      
        return this.http.get(path, options)
            .map((response: Response) => <Blob>response.blob())              
            .catch(this.handleError);
      }
      

      For using FileSaver.js put the following import to your component:

      import * as FileSaver from 'file-saver';
      

      To trigger the download use that:

      this.api.getFile("file.pdf")
      .subscribe(fileData => FileSaver.saveAs(fileData, "file.pdf"));
      
    0 讨论(0)
提交回复
热议问题