響應具有圖像數據,但我無法從響應中提取它。從響應中提取圖像數據:Angular2
客戶端代碼 -
download() {
this._http.get('http://localhost:9000/download/' + this._fileid)
.subscribe(
data => {
this.image = data;
},
err => console.log('Error is..:' + err)
);
}
服務器代碼 -
app.get('/download/:fileid', function(req, res) {
var id = req.params.fileid;
res.set('Content-Type', 'image/jpeg');
gfs.createReadStream({_id: id}).pipe(res);
});
[編輯] - 我已經適應我的代碼使用CustomXhr但卻我得到沒有數據是空BLOB。
CUSTOM XHR代碼 -
@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
build(): any {
let xhr = super.build();
xhr.responseType = "blob";
return <any>(xhr);
}
}
自舉代碼 - 導出函數main(initialHmrState?:任何):無極{
return bootstrap(App, [
...ENV_PROVIDERS,
...PROVIDERS,
...DIRECTIVES,
...PIPES,
...APP_PROVIDERS,
provide(BrowserXhr, { useClass: CustomBrowserXhr })
])
.catch(err => console.error(err));
HTTP請求 -
download() {
this._http.get('http://localhost:9000/download/' + this._fileid)
.toPromise()
.then(res => {
if (res.headers.get("Content-Type").startsWith("image/")) {
var blob = new Blob([new Uint8Array(res._body)], {
type: res.headers.get("Content-Type")
});
var urlCreator = window.URL;
var url = urlCreator.createObjectURL(blob);
console.log(url);
this.image = url;
}
})
}
感謝阿卜杜拉赫曼。你的方法有效。 – shiv
@shiv歡迎您,當然這只是一個解決方法,直到'arrayBuffer'或'blob'實現在angular2 – Abdulrahman