从响应中提取图像数据:Angular 2 [英] Extracting Image Data from response: Angular 2
本文介绍了从响应中提取图像数据:Angular 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
响应中包含图像数据,但是我无法从响应中提取图像.
The response has the image data but I am unable to extract it from the response.
客户代码-
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.
- I have adapted my code to use CustomXhr but however I get an empty blob with no data.
自定义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;
}
})
}
推荐答案
您正在寻找的是arrayBuffer()
.您的代码将是:
What you are looking for is arrayBuffer()
. Your code will be:
download() {
this._http.get('http://localhost:9000/download/' + this._fileid)
.subscribe(
data => {
this.image = data.arrayBuffer();
},
err => console.log('Error is..:' + err)
);
}
但是,不幸的是,从版本13开始,尚未实现arrayBuffer()
.
But, unfortunately, arrayBuffer()
is not yet implemented as of beta.13.
您可以改用XMLHttpRequest
,这是一个小矮人
getImage(url:string){
return Observable.create(observer=>{
let req = new XMLHttpRequest();
req.open('get',url);
req.responseType = "arraybuffer";
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
observer.next(req.response);
observer.complete();
}
};
req.send();
});
}
这篇关于从响应中提取图像数据:Angular 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文