在 Angular 4/5+ 中从 API 获取图像? [英] Getting Image from API in Angular 4/5+?

查看:28
本文介绍了在 Angular 4/5+ 中从 API 获取图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有新开发 Angular 4.我在从 API 获取有关显示图像的响应时遇到问题.在 API 中,图像文件具有输入流文件,我不知道如何检索它并正确显示它.

I have new to develop Angular 4. I have facing issue while getting response from API about display image.In API,an image file has input-stream file,I don't know how to retrieve it and display it properly.

有人能解决吗?

我试过了:

  • Image.Component.ts:

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()));           
});

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

Result of this => W29iamVjdCBCbG9iXQ== , but it was not correct format

也试过这个:

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 进行编码,它应该是错误,而不是拉丁范围

but I used to encode using window.btoa it should be error like not latin range

推荐答案

您应该在 GET-Request 设置中设置 responseType: ResponseContentType.Blob,因为这样您就可以将图像作为 blob 进行转换它后来是 base64 编码的源代码.你上面的代码不好.如果您想正确执行此操作,请创建单独的服务以从 API 获取图像.因为在组件中调用 HTTP-Request 不太好.

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

这是一个工作示例:

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

角 4:

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

Angular 5+:

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

重要提示:从 Angular 5+ 开始,您应该使用新的 HttpClient.

Important: Since Angular 5+ you should use the new HttpClient.

新的 HttpClient 默认返回 JSON.如果您需要其他响应类型,则可以通过设置 responseType: 'blob' 来指定.在此处阅读更多相关信息.

The new HttpClient returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'. Read more about that here.

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

Now you need to create some function in your image.component.ts to get image and show it in html.

要从 Blob 创建图像,您需要使用 JavaScript 的 FileReader.这是创建新的 FileReader 并监听 FileReader 的加载事件的函数.因此,此函数返回 base64 编码的图像,您可以在 img src-attribute 中使用该图像:

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:

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-function.这是一个示例函数:

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example function:

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 变量:

Now you can use your imageToShow-variable in HTML template like this:

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

我希望这个描述清晰易懂,你可以在你的项目中使用它.

I hope this description is clear to understand and you can use it in your project.

此处查看 Angular 5+ 的工作示例.

See the working example for Angular 5+ here.

这篇关于在 Angular 4/5+ 中从 API 获取图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆