从Java API中渲染byte[],作为Angular 2中的图像。

huangapple go评论85阅读模式
英文:

Render byte[] from Java API as an image in Angular 2

问题

我已经陷在这个问题上有一段时间了,非常感谢任何帮助。
图片以Base64存储,我就是无法正确设置: 

我在我的 ProductRestController 中有以下 API:

    @GetMapping("/{id}/image")
    public byte[] getProductImageByProductId(@PathVariable Long id) {
        return productFacade.getProductImageByProductId(id);
    }

我的 product.service.ts:

    getProductImageByProductId(productId: number) {
        return this.http.get(ServiceConfig.serverBaseUrl + `/product/${productId}/image`, {responseType: 'arraybuffer'});
    } // 我猜问题可能出在 responseType 上?我尝试过所有类型。。

在我的 select-product.component.ts 中:

    getProductImage(product: Product) {
        this.productService.getProductImageByProductId(product.id).subscribe( base64 => {
            if(base64) {
                this.base64 = 'data:image/jpg;base64,' + base64; // this.base64 是一个字符串
            }
            else {this.base64 = 'assets/no-image-icon.png';}
        });
    }

最后是 HTML:

    <img [escape]="false"
         pTooltip='<img style="max-height: 100%; max-width: 100%" src="{{base64}}">'
         tooltipPosition="right" (mouseover)="getProductImage(product)"
         src="assets/eye-icon.png" style="max-width: 100%; width: 80%; margin-bottom: 3px">

它应该在你悬停在图标上时,在工具提示中显示图像,但无论我在服务中设置什么样的 responseType,它都会给我一个解析错误,响应中会有一些类似于乱码的内容,样式如下:
%�S���cs5���&amp;D�TdE£t6�U�e���u��F'���������������Vfv��������7GWgw��������5!1AQaq"2...

感谢您的帮助!
英文:

i've been stuck on this one for a while and any help is appreciated.
Images are stored as Base64 and i just can't get the setup right:

I have the following API in my
ProductRestController

@GetMapping(&quot;/{id}/image&quot;)
public byte[] getProductImageByProductId(@PathVariable Long id) {
    return productFacade.getProductImageByProductId(id);
}

my product.service.ts:

  getProductImageByProductId(productId: number) {
    return this.http.get(ServiceConfig.serverBaseUrl + `/product/${productId}/image`, {responseType: &#39;arraybuffer&#39;});
  } // I guess it has to be something with the responseType? I tried all types..

in my select-product.component.ts:

  getProductImage(product: Product) {
      this.productService.getProductImageByProductId(product.id).subscribe( base64 =&gt; {
        if(base64) {
          this.base64 = &#39;data:image/jpg;base64,&#39; + base64; // this.base64 is a String
        }
        else {this.base64 = &#39;assets/no-image-icon.png&#39;;}
      });

and finally the html:

      &lt;img [escape]=&quot;false&quot;
           pTooltip=&#39;&lt;img style=&quot;max-height: 100%; max-width: 100%&quot; src=&quot;{{base64}}&quot; &gt;&#39;
           tooltipPosition=&quot;right&quot; (mouseover)=&quot;getProductImage(product)&quot;
           src=&quot;assets/eye-icon.png&quot; style=&quot;max-width: 100%; width: 80%; margin-bottom: 3px&quot;&gt;

}

It should show an image in a tooltip when you hover on an icon, but whatever responseType i'm setting in my service, it will give me a parsing error with in the response some gibberish in the style of :
%�S���cs5���&D�TdE£t6�U�e���u��F'���������������Vfv��������7GWgw��������5!1AQaq"2...

Thank you for your help!

答案1

得分: 1

你应该使用 responstype 为 blob。因为你返回的是字节而不是 base64 字符串。

因为这个 Java 的 getmapping 告诉你 "byte[]"

@GetMapping("/{id}/image")
public byte[] getProductImageByProductId(@PathVariable Long id) {
    return productFacade.getProductImageByProductId(id);
}
getProductImageByProductId(productId: number): Observable<any> {
    return this.http.get(ServiceConfig.serverBaseUrl + `/product/${productId}/image`, {responseType: 'blob'});
}
export class SelectProductComponent {

    constructor(private sanitizer: DOMSanitizer, /*other params*/) {}

    public someMethod(product: Product): void {
        this.productService.getProductImageByProductId(product.id).subscribe(data => {
            var reader = new FileReader();
            const blob = new Blob([data], {
                type: 'image/jpeg'
            });
            // EDIT: Don't use function. my bad
            reader.onloadend = () => {
                const untrustedData = reader.result;
                this.base64 = this.sanitizer.bypassSecurityTrustUrl(untrustedData);
            }
            reader.readAsDataURL(blob);
        });
    }

    // also you can use ObjectURL if you 
    // just want the image and don't need the conversion to base64

    public someOtherMethod(product: Product): void {
        this.productService.getProductImageByProductId(product.id).subscribe(data => {
            const blob = new Blob([data], {
                type: 'image/jpeg'
            });
            const objectUrl = URL.createObjectURL(blob);
            this.image = this.sanitizer.bypassSecurityTrustUrl(objectURL);
        });
    }

}
英文:

You should use responstype blob. since you return byte and not base64 string.

Because this Java getmapping tells you "byte[]"

@GetMapping(&quot;/{id}/image&quot;)
public byte[] getProductImageByProductId(@PathVariable Long id) {
    return productFacade.getProductImageByProductId(id);
}
  getProductImageByProductId(productId: number): Observable&lt;any&gt; {
    return this.http.get&lt;Observable&lt;any&gt;&gt;(ServiceConfig.serverBaseUrl + `/product/${productId}/image`, {responseType: &#39;blob&#39;});
  } /
   export class SelectProductComponent{

    constructor(private sanitizer:DOMSanitizer, /*other params*/){}


    public someMethod(product:Product):void{
    this.productService.getProductImageByProductId(product.id).subscribe( data =&gt;{
         var reader = new FileReader();
         const blob = new Blob([data], {
            type: &#39;image/jpeg&#39;
             });
         //EDIT: Don&#39;t use function. my bad
         reader.onloadend = () =&gt; {
           const untrustedData = reader.result; 
           this.base64 = this.sanitizer.bypassSecurityTrustUrl(untrustedData);          
         } 
         reader.readAsDataURL(blob); 
         
       }
 
    }

   
       // also you can use ObjectURL if you 
      //just want the image and don&#39;t need the conversion to base64

   
        public someOtherMethod(product:Product):void{
    this.productService.getProductImageByProductId(product.id).subscribe( data =&gt;{
            const blob = new Blob([data], {
            type: &#39;image/jpeg&#39;
             });
           const objectUrl = URL.createObjectURL(blob);
           this.image = this.sanitizer.bypassSecurityTrustUrl(objectURL);
         }
       }
 
    }

}

答案2

得分: 0

关于将Base64编码的字符串作为响应返回,您怎么看?

@GetMapping("/{id}/image")
public String getProductImageByProductId(@PathVariable Long id) {
    byte[] image = productFacade.getProductImageByProductId(id);
    return Base64.getEncoder().encodeToString(image);
}

注意:如果您的数据库中有以Base64编码的图像,只需将其作为响应返回即可。

英文:

What do you think about returning base64 encoded string as response ?

@GetMapping(&quot;/{id}/image&quot;)
public String getProductImageByProductId(@PathVariable Long id) {
    byte[] image = productFacade.getProductImageByProductId(id);
    return Base64.getEncoder().encodeToString(image);
}

Note: Is you have images as bas64 in the db, just return it as response.

huangapple
  • 本文由 发表于 2020年8月17日 22:59:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63453463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定