我需要显示服务发送的图像。我的angular2应用会收到hex string
,我将其转换为byteArray
,然后转换为blob
,然后转换为file
。在我的console.log中,我看到转换后的文件:
File(1975561) {name: "uploaded_file.jpg", lastModified:
1528145682995, lastModifiedDate: Mon Jun 04 2018 16:54:42 GMT-040....
如果我在新窗口中打开它,会发生同样的事情。 我检查了十六进制文件在线转换器中十六进制字符串是否正确,我得到了正确的文件。所以我的十六进制是正确的 我的代码是:
Service:
public hexToFile(hex): Observable<any> {
return Observable.create(observer => {
let bytes = [];
for ( let i = 0; i < hex.length; i += 2) {
bytes.push(parseInt(hex.substr(i, 2), 16));
}
let blob = new Blob(bytes, { type: "image/jpeg" });
let file = new File([blob], "uploaded_file.jpg", {type: "image/jpeg", lastModified: Date.now()});
observer.next(file);
});
}
Component:
public showFile(hex) {
let _self = this;
this.service.hexToFile(hex).subscribe(file => {
let url = URL.createObjectURL(file);
_self.sanitizedUrl = _self.sanitizer.bypassSecurityTrustUrl(url);
});
}
<div *ngIf="image">
<img src=`{{sanitizedUrl}}` width="500px"/>
</div>