从角度为4/5 + 的 API 中获取图像?

我是新的开发使用角度4。我面临一个问题,而得到一个有关显示图像的 API 响应。在 API 中,图像文件有一个输入流文件。我不知道怎么把它找回来,好好展示一下。

有人能解决吗?

我试过了:

  • 图片组件:

     this.http.get('http://localhost:8080/xxx/download/file/596fba76ed18aa54e4f80769')
    .subscribe((response) => { var blob = new Blob([response.text()], {type: "image/png"});
    console.log(blob);
    console.log(window.btoa(blob.toString()));
    });
    

结果为 this = > W29iamVjdCBCbG9iXQ==,但格式不正确

也试过这个:

this.http.get('http://localhost:8080/xxx/download/file/596fba76ed18aa54e4f80769').map(Image=>Image.text())
.subscribe(data => {
console.log((data.toString()));
});

结果是这样的 = >

 ����\ExifII*��7                                                      ��DuckyK��fhttp://ns.adobe.com/xap/1.0/<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.3-c011 66.145661, 2012/02/06-14:56:27        "> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:stRef="http://ns.adobe.com/xap/1.0/sType/ResourceRef#" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmpMM:OriginalDocumentID="xmp.did:0280117407206811A2188F30B3BD015B" xmpMM:DocumentID="xmp.did:E2C71E85399511E7A5719C5BBD3DDB73" xmpMM:InstanceID="xmp.iid:E2C71E84399511E7A5719C5BBD3DDB73" xmp:CreatorTool="Adobe Photoshop CC 2014 (Windows)"> <xmpMM:DerivedFrom stRef:instanceID="xmp.iid:7092a9cd-b3fd-bb49-b53c-9b6e1aa1ac93" stRef:documentID="adobe:docid:photoshop:40615934-3680-11e7-911d-f07c687d49b8"/> <dc:rights> <rdf:Alt> <rdf:li xml:lang="x-default">                                                      </rdf:li> </rdf:Alt> </dc:rights> <dc:creator> <rdf:Seq/> </dc:creator> </rdf:Description> </rdf:RDF> </x:xmpmeta> <?xpacket end="r"?>���Photoshop 3.08BIMJZ%Gt6                                                      8BIM%�<".}��νz��܌��Adobed����

但我过去常用 window.btoa 编码,它应该是错误的,不像拉丁范围。

149171 次浏览

您应该在 GET-Request 设置中设置 responseType: ResponseContentType.Blob,因为这样您可以将映像作为 blob 获取,并在稍后将其转换为 da base64编码的源代码。你上面的代码不好。如果您希望正确地执行此操作,那么创建单独的服务以从 API 获取图像。因为在组件中调用 HTTP-Request 是不好的。

下面是一个实际的例子:

创建 image.service.ts并输入以下代码:

角度4:

getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}

角5 + :

getImage(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, { responseType: 'blob' });
}

重要提示: 由于角度5 + ,你应该使用新的 HttpClient

新的 HttpClient默认返回 JSON。如果需要其他响应类型,可以通过设置 responseType: 'blob'来指定。阅读更多关于 给你的内容。

现在您需要在 image.component.ts中创建一些函数来获取图像并用 html 显示它。

要从 Blob 创建图像,需要使用 JavaScript 的 FileReader。 下面是创建新 FileReader并监听 FileReader 的 load-Event 的函数。结果,该函数返回 base64编码的图像,您可以在 img src-tribute 中使用该图像:

imageToShow: any;


createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);


if (image) {
reader.readAsDataURL(image);
}
}

现在应该使用创建的 ImageService从 api 获取图像。你应该订阅数据,并把这个数据给 createImageFromBlob-函数。下面是一个示例函数:

getImageFromService() {
this.isImageLoading = true;
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
});
}

现在您可以像下面这样在 HTML 模板中使用 imageToShow变量:

<img [src]="imageToShow"
alt="Place image title"
*ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
<img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

我希望这个描述是清楚的理解,您可以在您的项目中使用它。

参见角度5 + 给你的工作示例。

角度5:

 getImage(id: string): Observable<Blob> {
return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

没有必要使用角 http,您可以使用 js 本机函数获得

// you will ned this function to fetch the image blob.
async function getImage(url, fileName) {
// on the first then you will return blob from response
return await fetch(url).then(r => r.blob())
.then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform
         

return new File([blob], fileName+'.'+   blob.type.split('/')[1]) ;
});
}


// example url
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';


// calling the function
getImage(url, 'your-name-image').then(function(file) {


// with file reader you will transform the file in a data url file;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
    

// just putting the data url to img element
document.querySelector('#image').src = reader.result ;
}
})
<img src="" id="image"/>