Javascript 使用http获取图像或字节数据
对于web应用程序,我需要使用ajax请求获取图像,因为我们的API上有签名+身份验证,所以我们无法使用简单的Javascript 使用http获取图像或字节数据,javascript,angular,angular2-http,Javascript,Angular,Angular2 Http,对于web应用程序,我需要使用ajax请求获取图像,因为我们的API上有签名+身份验证,所以我们无法使用简单的 由于我们使用的是angular2,我们显然在寻找blob或类似的东西,但正如static\u response.d.ts文件中所述: /** * Not yet implemented */ blob(): any; 所以好吧,我现在不能做,我必须等待这个功能的实现 但问题是我等不及了,所以我需要一个修补程序或一点小技巧,以便能够从响应中获取图像数据,并且我将能够删除我的技巧,并
由于我们使用的是angular2,我们显然在寻找blob或类似的东西,但正如static\u response.d.ts
文件中所述:
/**
* Not yet implemented
*/
blob(): any;
所以好吧,我现在不能做,我必须等待这个功能的实现
但问题是我等不及了,所以我需要一个修补程序或一点小技巧,以便能够从响应中获取图像数据,并且我将能够删除我的技巧,并在实现时将blob()
方法调用设置为良好
我试过这个:
export class AppComponent {
constructor(private api:ApiService, private logger:Logger){}
title = 'Tests api';
src='http://placekitten.com/500/200'; //this is src attribute of my test image
onClick(){ //Called when I click on "test" button
this.api.test().then(res => {
console.log(res._body);
var blob = new Blob([new Uint8Array(res._body)],{
type: res.headers.get("Content-Type")
});
var urlCreator = window.URL;
this.src = urlCreator.createObjectURL(blob);
});
}
}
使用ApiService.test()
方法:
test():Promise<any> {
return this.http.get(this._baseUrl + "myapi/example/145", this.getOptions())
//getOptions() is just creating three custom headers for
//authentication and CSRF protection using signature
.toPromise()
.then(res => {
this.logger.debug(res);
if(res.headers.get("Content-Type").startsWith("image/")){
return res;
}
return res.json();
})
.catch(res => {
this.logger.error(res);
return res.json();
} );
}
test():承诺{
返回this.http.get(this.\u baseUrl+“myapi/example/145”,this.getOptions())
//getOptions()正在为创建三个自定义标题
//使用签名的身份验证和CSRF保护
.toPromise()
。然后(res=>{
this.logger.debug(res);
if(res.headers.get(“Content Type”).startsWith(“image/”){
返回res;
}
返回res.json();
})
.catch(res=>{
此.logger.error(res);
返回res.json();
} );
}
但我没有从中得到任何图像,记录响应数据时会显示一个大字符串,即图像数据
您是否有实现此目的的技巧?此JSFIDLE可以帮助您: 正如您所希望的,该方法是从提供的URL创建Blob
// Image returned should be an ArrayBuffer.
var xhr = new XMLHttpRequest();
xhr.open( "GET", "https://placekitten.com/500/200", true );
// Ask for the result as an ArrayBuffer.
xhr.responseType = "arraybuffer";
xhr.onload = function( e ) {
// Obtain a blob: URL for the image data.
var arrayBufferView = new Uint8Array( this.response );
var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
var img = document.querySelector( "#photo" );
img.src = imageUrl;
};
xhr.send();
我认为您没有根据您的请求设置
响应类型。现在有点棘手,因为它不受支持
解决方法是重写BrowserXhr
类,在xhr
对象本身上设置responseType
您可以扩展浏览器xhr
:
@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
constructor() {}
build(): any {
let xhr = super.build();
xhr.responseType = 'arraybuffer';
return <any>(xhr);
}
}
问题在于,您没有覆盖所有请求。在引导级别,它将覆盖所有内容。因此,您可以在受影响组件的提供程序属性内的子注入器中提供它
这是一个工作程序:。不再需要扩展浏览器xhr
。(按照第2.2.1节的规定进行试验)
现在有一个属性responseType:ResponseContentType
,可以设置为ResponseContentType.Blob
使用消毒剂
import {DomSanitizer} from '@angular/platform-browser';
此示例还创建了一个经过清理的url,该url可以绑定到
的src
属性
使用新的Angular HttpClient很容易实现这一点。与tschuege的方法不同的是:
return this._http.get('/api/images/' + _id, {responseType: 'blob'}).map(blob => {
var urlCreator = window.URL;
return this._sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})
关键是将responseType设置为'blob',这样它就不会试图将其解析为JSON问题是这是一个完整的JS解决方案,我需要一个TS hack,它可以通过Response object实现,以便在blob()函数可用时易于删除。因此,我将有两个http提供程序,一个用于字节请求,另一个用于JSON请求?是的,对于返回json的请求,默认的是一个,对于返回二进制的请求,自定义的是一个……我在我的answer@ThierryTemplier嘿,这个笨蛋不工作了。你能在这里更新它或更新代码吗?谢谢。今天您可以使用res=>res.blob()
。在Angular use的较新版本中标题:new-HttpHeaders().append('Content-Type','image/jpg')
效果非常好!谢谢
this.http.get(url, {
headers: {'Content-Type': 'image/jpg'},
responseType: ResponseContentType.Blob
})
.map(res => {
return new Blob([res._body], {
type: res.headers.get("Content-Type")
});
})
.map(blob => {
var urlCreator = window.URL;
return this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})
return this._http.get('/api/images/' + _id, {responseType: 'blob'}).map(blob => {
var urlCreator = window.URL;
return this._sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})