【问题标题】:Getting Image from API in Angular 4/5+?在 Angular 4/5+ 中从 API 获取图像?
【发布时间】:2018-01-13 19:20:43
【问题描述】:

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

有人能解决吗?

我试过了:

  • 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== ,但格式不正确

也试过了:

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

【问题讨论】:

  • 查看this post
  • 我尝试了该链接,但它显示为“unsafe:blob:localhost:4200/47c05912-5beb-41bf-a791-ca8f0d86f6afnet::ERR_UNKNOWN_URL_SCHEME”,并且该 uri 具有直接图像
  • @KarthicG 如果您使用的是 Angular,您可能会收到该错误。使用DomSanitizer.bypassSecurityTrustUrl 修复它。

标签: angular typescript angular2-services


【解决方案1】:

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

这是一个工作示例:

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

Angular 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

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

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

要从 Blob 创建图像,您需要使用 JavaScript 的 FileReader。 这是创建新的FileReader 并监听 FileReader 的加载事件的函数。结果这个函数返回base64编码的图像,你可以在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。这是一个示例函数:

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-variable:

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

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

查看 Angular 5+ here 的工作示例。

【讨论】:

  • @malkoto1 我知道,因为我没有时间更新这个答案。在 Angular 5 中,您应该使用 HttpClient 而不是 Http。
  • 好吧,我已经让它与 HttpClient 一起工作,但不知何故它试图解析 JSON 并给出以下错误:SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data .如果您有时间在不久的将来更新它,我将不胜感激:)
  • 我也必须传递标题。所以我的电话是:返回这个 httpClient.get('url', {headers: this.httpHeaders});那么,我应该如何通过 {response-type:'blob'} ?
  • @RahulSharma 你可以这样做:return this httpClient.get('url', {headers: this.httpHeaders, responseType: 'blob' });
  • 阅读器负载监听器中的isImageLoading变量不应该设置为false吗?
【解决方案2】:

角度 5:

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

【讨论】:

  • 我也必须传递标题。所以我的电话是:返回这个 httpClient.get('url', {headers: this.httpHeaders});那么,我应该如何通过 {response-type:'blob'} ?
  • { headers: this.httpHeaders, responseType: 'blob' }
【解决方案3】:

不需要使用angular 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 ;
    }
})
&lt;img src="" id="image"/&gt;

【讨论】:

    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 2018-10-24
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    相关资源
    最近更新 更多