下载文件的正确方法是使用responseType: 'blob'。
这里也是传递 Auth Header 的示例。这不是必需的,但是您可以查看 HttpClient 的 get 方法以了解更多关于如何构造它以发送额外的标头。
//service
public downloadExcelFile() {
const url = 'http://exmapleAPI/download';
const encodedAuth = window.localStorage.getItem('encodedAuth');
return this.http.get(url, { headers: new HttpHeaders({
'Authorization': 'Basic ' + encodedAuth,
'Content-Type': 'application/octet-stream',
}), responseType: 'blob'}).pipe (
tap (
// Log the result or error
data => console.log('You received data'),
error => console.log(error)
)
);
}
HttpClient get().
/**
* Construct a GET request which interprets the body as an `ArrayBuffer` and returns it.
*
* @return an `Observable` of the body as an `ArrayBuffer`.
*/
get(url: string, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<ArrayBuffer>;
您可以像这样在组件中使用它。
datePipe = new DatePipe('en-Aus');
onExport() {
this.service.downloadExcelFile().subscribe((res) => {
const now = Date.now();
const myFormattedDate = this.datePipe.transform(now, 'yyMMdd_HH:mm:ss');
saveAs(res, `${this.docTitle}-${myFormattedDate}.xlsx`);
}, error => {
console.log(error);
});
}
我使用来自 @angular/common 的 DatePipe 使文件名独一无二。
我还使用了文件保护程序来保存文件。
通过在下面添加这些包来导入文件保护程序安装文件保护程序。
npm install -S file-saver
npm install -D @types/file-saver
并且在你的组件中添加 import 语句。
import { saveAs } from 'file-saver';