Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...