[英]Downloading an excel file in angular client (angular v5.2) received as a response from WebAPI
我有以下服務,可讓我使用http Get下載文件
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { saveAs } from 'file-saver';
@Injectable()
export class FileService {
blob: Blob;
url: string;
constructor(private _http: Http) { }
uploadFile(file: File, filetype: string) {
console.log('uploading...');
const endpoint = 'http://localhost:60994/api/file';
const formData: FormData = new FormData();
formData.append(filetype, file, file.name);
return this._http.post(endpoint, formData);
}
getFile() {
return this._http.get('http://localhost:60994/api/file')
.subscribe(data => {
if (data != null)
{
this.blob = new Blob([data._body], { type: 'application/vnd.ms-excel' });
const file = new File([this.blob], 'report.xlsx', { type: 'application/vnd.ms-excel' });
console.log(this.blob);
console.log(file);
this.url = window.URL.createObjectURL(file);
window.open(this.url);
}
});
}
}
下載時的文件(xlsx,xls)大部分已損壞,沒有數據(服務器發送的文件中有數據,我自己檢查過)。 另外,
console.log(this.blob);
和
console.log(file);
顯示文件,其大小幾乎與服務器預期的大小相同(在chrome的控制台中)。
我想到的最好的猜測是,我在重建接收到的文件時出錯了。
您的http GET請求很可能需要一些選項來表示您對原始響應字節感興趣:
this._http.get(url, {responseType: 'blob'}).subscribe(..)
我不確定您的呼叫的'TRIAL_PRICE'
參數當前是什么,但這肯定不是angular5 HTTP客戶端期望的參數:
通過將responseType設置為blob進行調用,您還將獲得一個Blob對象作為Observable有效負載,因此您也不需要正文轉換邏輯。
原來我為HTTP GET使用了錯誤的導入(Http)。
import { HttpClient } from '@angular/common/http';
導入import { HttpClient } from '@angular/common/http';
並改變了
getFile() {
return this._http.get('http://localhost:60994/api/file',{responseType: 'blob'})
.subscribe(data => saveAs(data));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.