4

I'm trying to be able to display images that can be edited in the back end, but these have to be available while offline too. To acomplish this goal I'm downloading these images with the following method (which is the only one that worked for me)

download_save_picture(picture_url) {
  let splited_url = picture_url.split('/');
  var filename = splited_url[splited_url.length - 1];

  var config = { responseType: 'blob' as 'blob' };

  this.httpClient.get(picture_url, config).subscribe(
    data => {
      this.file.writeFile(this.file.dataDirectory, filename, data, { replace: true });
    },
    err => console.error(err),
    () => { }
  );
}

And then I can verify that these files exist and that their weight is also different from 0, so I guess everyting is correct until this point.

this.file.checkFile(this.file.dataDirectory, filename)
.then(() => {
  alert("File Exist!!!");  // I always enter here
})
.catch((err) => {
  alert("ERR : " + err);
});

this.file.resolveLocalFilesystemUrl(this.file.dataDirectory + filename).then((entry: any)=>{
  entry.getMetadata((metadata) => {
      alert("SIZE: " + metadata.size);
  })
}).catch((error)=>{
  alert(error);
});

So the next step is to display the image which is in the path this.file.dataDirectory + filename, how can I do this?

After searching for a solution and reading I understand that I have to:

  1. Load the file binary content.

  2. Convert this binary content to base 64.

  3. Then display it with src="data:image/jpeg;base64,"+{{image_in_base64}};

But until now I've not been able to do steps 1 (load the file content) and 2 (convert it to base 64), how can I do that?

Patricio Sard
  • 2,092
  • 3
  • 22
  • 52
  • This may sound stupid but assuming you can read the file from disk can't you just point your image src to the file on disk? – Mathyn Jan 04 '19 at 14:02
  • @Mathyn I tried `src={{full_path_image}}`, but it didn't work, that's what you mean? – Patricio Sard Jan 04 '19 at 14:09
  • Did you get any errors when doing this? e.g. a 404 or something else? – Mathyn Jan 04 '19 at 14:09
  • For the 1st and 2nd step try somehting like this : https://stackoverflow.com/questions/32833797/convert-local-image-to-base64-string-in-javascript – andrea06590 Jan 04 '19 at 14:13
  • @Mathyn The `this.file.writeFile(this.file.dataDirectory, filename, data, { replace: true });` doesn't work in a browser so I have to test iit in an actual Android device. In my case when I use `src={{full_path_image}}` the entire Page is not even displayed, but removing that makes everything work fine. – Patricio Sard Jan 04 '19 at 14:15
  • Try sanitizing your url using `import { DomSanitizer} from '@angular/platform-browser'; cleanurl =this.sanitizer.bypassSecurityTrustUrl("filepath");` and then use the cleanurl in the source. – Ahmed Shabib Jan 05 '19 at 09:08

2 Answers2

1

At the end it was easier and faster to use LocalStorage instead of files

First I made the function download_save_picture(picture_url) which save the content of the image in picture_url in Base64 in localStorage(key), the key will be everything after the last /, so if we use the URL https://www.w3schools.com/w3css/img_lights.jpg the content will be saved in icon.img_lights.jpg.

download_save_picture(picture_url) {
  let splited_url = picture_url.split('/');
  var name = splited_url[splited_url.length - 1];

  if (localStorage.getItem('icon.' + name) === null) {
    var config = { responseType: 'blob' as 'blob' };

    this.httpClient.get(picture_url, config).subscribe(
      data => {
        var reader = new FileReader();

        reader.readAsDataURL(data);

        reader.onload = function() {
          window.localStorage.setItem('icon.' + name, reader.result);
        }
      },
      err => console.error(err),
      () => { }
    );
  }
}

Then at the view I display the image with <img src={{useLocalImage(item.image)}}></p>, where useLocalImage simply returns the content saved in localStorage.

useLocalImage(picture_url) {
  let splited_url = picture_url.split('/');
  var name = splited_url[splited_url.length - 1];

  var icon_name = window.localStorage.getItem('icon.' + name);

  return icon_name;
}
Patricio Sard
  • 2,092
  • 3
  • 22
  • 52
  • When doing this please keep in my mind limits apply to localstorage. See [this](https://stackoverflow.com/questions/2989284/what-is-the-max-size-of-localstorage-values) question for some more info. – Mathyn Jan 08 '19 at 08:13
0

Following is the code that worked for me.

<input #fileinput type="file" [(ngModel)]="file_obj" (click)="resetFileInput()" (change)="onUploadChange()"/>

Then in your typescript code.

@ViewChild('fileinput') file_input;
file_obj:any;
onUploadChange() {
    const file = this.file_input.nativeElement.files[0];
    const fReader = new FileReader();
    fReader.readAsDataURL(file);
    fReader.onloadend = function(event) {
    //do whatever you want with the result here.
      console.log(event.target['result']);
    };
  }
 resetFileInput() {
    this.file_input.nativeElement.value = '';
  }

UPDATE - If you are using Ionic Native File or Cordova File Plugin

Ionic Native file is different from the browser File object. There seems to be a method called getFile() , which returns FileEntry object This has something called method .file() which returns a Native file object . And then use the FileReader to read the file as dataURL using readAsDataURL method.

Ahmed Shabib
  • 687
  • 1
  • 8
  • 16
  • Where do I put the `file path`? – Patricio Sard Jan 04 '19 at 14:30
  • In the browser, you won't be able to give the file path to open a file, you need to select it via the input file field. If you are using a Cordova library , then you need to refer to that documentation. – Ahmed Shabib Jan 05 '19 at 08:35
  • There seems to be a method called getFile() https://ionicframework.com/docs/native/file/#getFile , which returns FileEntry object, this has something called .file method you could use this to get the file object https://cordova.apache.org/docs/en/1.8.0/cordova/file/fileentry/fileentry.html And thenn use the FileReader to read the file as dataURL – Ahmed Shabib Jan 05 '19 at 08:39