ngx-filesaver
Simple file save with FileSaver.js
![Build Status](https://travis-ci.org/cipchk/ngx-filesaver.svg?branch=master)
中文版
Examples
Installation
npm install file-saver ngx-filesaver --save
Add the FileSaverModule
module to your project:
import { FileSaverModule } from 'ngx-filesaver';
@NgModule({
imports: [ FileSaverModule ]
})
Instructions
There are two ways to save a file: using FileSaverService.save()
or using the fileSaver
directive.
1、FileSaverService
constructor(private _http: Http, private _FileSaverService: FileSaverService) {
}
onSave() {
let options = new RequestOptions({
responseType: ResponseContentType.Blob
});
this._http.get('demo.pdf', options).subscribe(res => {
this._FileSaverService.save((<any>res)._body, fileName);
});
}
2、fileSaver directive
Configuration example
<button type="button"
fileSaver
[method]="'GET'"
[fileName]="'中文pdf.pdf'"
[url]="'assets/files/demo.pdf'"
[header]="{ token: 'demo' }"
[query]="{ pi: 1, name: 'demo' }"
(success)="onSuc($event)"
(error)="onErr($event)">Download PDF</button>
fileSaver: the directive name
Parameters
Parameter | Description | Type | Default |
---|
method | Request method type | string | GET |
url | Request URL | string | - |
fileName | Filename when downloading | string | - |
query | Additional query parameters. Equivalent to params value | string | - |
header | Header configuration. Usually used for especifying access tokens | any | - |
success | Download success callback | EventEmitter<any> | - |
error | Download error callback | EventEmitter<any> | - |
Custom HTTP type
<button type="button"
fileSaver
[http]="onRemote('pdf', true)">Download PDF</button>
onRemote(type: string, fromRemote: boolean): Observable<Response> {
let options = new RequestOptions({
responseType: ResponseContentType.Blob
});
return this._http.get(`assets/files/demo.${type}`, options).map(response => {
response.headers.set('filename', `demo.${type}`)
return response;
});
}
About filenames
The name for the downloaded file is obtained with the following priority:
- fileName
- response.headers.get('filename')
- response.headers.get('x-filename')。
If you are requesting a CORS address, you need to pay attention to the request headers. Setting Access-Control-Allow-Headers: filename
should be sufficient