响应具有图像数据,但我无法从响应中提取它。
客户代码-
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。
自定义 XHR 代码-
@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
build(): any {
let xhr = super.build();
xhr.responseType = "blob";
return <any>(xhr);
}
}
引导代码-
export function main(initialHmrState?: any): Promise<any> {
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;
}
})
}