下载文件以angular2的形式发送 [英] 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?
推荐答案
您有两种可能:
-
如果后端通过单击链接将文件直接发送到浏览器,则后端应在标头中使用内容类型application/octet-stream.这会导致浏览器询问用户如何保存/打开文件.
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.
如果通过Angular代码(Http模块)从后端加载文件,则可以使用filesaver.js或类似的库.这样您就可以完全控制并可以自己提示用户.
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
服务中的代码:
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);
}
要使用FileSaver.js,请将以下导入内容添加到您的组件中:
For using FileSaver.js put the following import to your component:
import * as FileSaver from 'file-saver';
要触发下载,请使用:
this.api.getFile("file.pdf")
.subscribe(fileData => FileSaver.saveAs(fileData, "file.pdf"));
这篇关于下载文件以angular2的形式发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!