Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

node.js - Download file sent in response angular2

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...