6

I'm trying to set an arraybuffer as source of an image tag. It seems that I've got 2 problems. My console is logging:

GET unsafe:data:image/jpg;base64, [object ArrayBuffer] net::ERR_UNKNOWN_URL_SCHEME

so my question is:
1. How do I convert my 'blob' to a string?
(if necessary: 2. How to remove the unsafe flag?)

html:

<img src="data:image/jpg;base64, {{blob}}">

ts (blob is transferred):

export class ImgViewerComponent implements OnInit {

    @Input('blob') blob: ArrayBuffer;

    constructor() { }

    ngOnInit() {
    }

}
1
  • Are trying to show image from file upload control? Commented Dec 11, 2018 at 12:54

1 Answer 1

10

Okay found some good solutions:

  1. Converting ArrayBuffer to string:

    function _arrayBufferToBase64( buffer ) {
      var binary = '';
      var bytes = new Uint8Array( buffer );
      var len = bytes.byteLength;
      for (var i = 0; i < len; i++) {
         binary += String.fromCharCode( bytes[ i ] );
      }
      return window.btoa( binary );
    }
    

    ArrayBuffer to base64 encoded string

  2. Remove the unsafe prefix:

    import {DomSanitizer} from '@angular/platform-browser';
    ...
    constructor(private sanitizer:DomSanitizer){}
    ...
    sanitize( url:string ) {
      return this.sanitizer.bypassSecurityTrustUrl(url);
    }
    

    How to avoid adding prefix “unsafe” to link by Angular2?

Now my Html looks like the following:

<img [src]="sanitize('data:image/jpg;base64, ' + _arrayBufferToBase64(blob))">
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, This solution worked for me. But I want to open image or file in another tab, How can i achieve the same using this solution? Thank you.
@AkshayDusane You can wrap the image tag with href. It'll pass your image to the link as content. See this question stackoverflow.com/questions/3139811/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.