Recently in ionic2 I faced a weird problem when using camera plugin in android . My app simply allows user to either take picture from camera or select image from gallery. When user takes picture from camera everything works fine but if user selects image from gallery , image is not displayed (using img tag). Very first difference i spotted between camera and gallery image was the uri of file. Camera image has following format
I tried adding different variants in config.xml but nothing worked so I debugged the whitelist plugin and it appeared that angular was adding unsafe: keyword to the beginning of content:// url. So the whole uri passed to whitelist plugin was like this
Here are relevant snippet of codes to make it work
Add DomSanitizer
file:///path/to/image.jpgwhere gallery image has following format
content://media/external/image/238I debugged my project using Android Studio and I found that when i try to display gallery image using img tag , following error is shown in console
URL blocked by whitelistIt was clear that whitelist plugin is blocking content:// requests so I tried to add content:// as whitelisted uri in my config.xml . I added the following lines
<access origin="content://*" /><allow-nagivation href="content://*" />BUT TO NO AVAIL.
I tried adding different variants in config.xml but nothing worked so I debugged the whitelist plugin and it appeared that angular was adding unsafe: keyword to the beginning of content:// url. So the whole uri passed to whitelist plugin was like this
unsafe:content://media/external/image/238After trying different methods finally I found something in angular documentation called DomSantizier. This class provides method to bypass security trust when dealing with unsafe url. I used bypassSecurityTrustUrl function of this class.
Here are relevant snippet of codes to make it work
Add DomSanitizer
import {DomSanitizer} from '@angular/platform-browser';Reference it in your component's constructor
constructor(private sanitizer:DomSanitizer, .....Create a helper method to which we will pass our unsafe url and it will call bypassSecurityTrustUrl on that url.
sanitize(url:string){ return this.sanitizer.bypassSecurityTrustUrl(url);}Now in our html we will call this sanitize url and pass the image url. Here is what my img looks like
<img [src]="sanitize(image)" />image is a variable that contains our image file uri.
Comments
Post a Comment
Share your wisdom