Janik
Janik

Reputation: 121

Ionic3, displaying images from sd (or any) storage on android

I am working on an app which takes images from an external api and then saves them to the device for offline use later on, which is essential. This is currently done via the cordova-plugin-filetransfer. They are stored in cordova.file.externalRootDirectory on my testing device now - I can see them and the files are okay.

Now I want to display these Images in a page, but however I do it - nothing works. So before ending things for today I thought I'd ask.

<img src="{{director.data_dir}}{{project.picture_path}}" /><br />
<p>{{director.data_dir}}{{project.picture_path}}</p>
<img [attr.src]="director.display_path(project.picture_path)" /><br />
<p>{{director.display_dir}}{{project.picture_path}}</p>

None of them work. I've tried several other ways, but I still get no image. The director.display_path() strips the file:// from the path as I've read I need to do this to get rid of this error:

Not allowed to load local resource: file:///storage/emulated/0/

Okay guys, what am I doing wrong? What should I do else?

Upvotes: 0

Views: 952

Answers (1)

roiko
roiko

Reputation: 33

I had the same problem, here it is how I solved. You need DomSanitizer and File: Install ionic-native/file (https://ionicframework.com/docs/native/file/)

Assume you have 2 parameters:

mypath = "file:///emulated/0/Android/data/... .../yourfolder/"

myimage = "yourimage.jpg"

In page.html file declare as:

<img [src]="cop">

Then in page.ts file: - Import DomSanitizer and File

import {DomSanitizer} from '@angular/platform-browser'
import { File } from '@ionic-native/file';
  • Inject them in constructor():

    constructor(private file: File, private sanitizer: DomSanitizer)

  • Set value of cop:

getSanitizedImage(path, imageName){
      this.file.readAsDataURL(path, imageName)
      .then((data)=>{
        let sanitized = this.sanitizer.bypassSecurityTrustUrl(data);
        this.cop=sanitized;
      })
      .catch((err)=>{
        console.log("error: " + JSON.stringify(err));
      });
  }

Now, just call getSanitizedImage(mypath, myimage), your variable "pos" will be updated and the <img> object will display your image

Upvotes: 3

Related Questions