Eran Levi
Eran Levi

Reputation: 363

Ionic2: Load and Save image to device using cordova-file-transfer

I'm working on app in Ionic2 and I'm downloading an image using "cordova-plugin-file-transfer" with the following code thanks to(ionic-2-file-transfer-example):

  downloadImage(image, name) {
      this.platform.ready().then(() => {
        const fileTransfer = new FileTransfer();
        let targetPath; // storage location depends on device type.

        // make sure this is on a device, not an emulation (e.g. chrome tools device mode)
        if(!this.platform.is('cordova')) {
          return false;
        }

        if (this.platform.is('ios')) {
          targetPath = cordova.file.documentsDirectory + name;
        }
        else if(this.platform.is('android')) {
          targetPath = cordova.file.dataDirectory + name;
        }
        else {
          // do nothing, but you could add further types here e.g. windows/blackberry
          return false;
        }

        fileTransfer.download(encodeURI(image), targetPath,
            (result) => {
         //Here i need to load it back
         this.img = targetPath; // <<-- ERROR -> Can't load from device
            },
            (error) => {
     console.log("error: "+error);
            }
        );
      });
    }

Its working perfectly (The image is saved on the device), the thing is, I need to load this image (that I stored in my device) in my app.

I saw the following code in this cordova library:

function readBinaryFile(fileEntry) {
    fileEntry.file(function (file) {
        var reader = new FileReader();

        reader.onloadend = function() {

            console.log("Successful file read: " + this.result);
            // displayFileData(fileEntry.fullPath + ": " + this.result);

            var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
            displayImage(blob);
        };

        reader.readAsArrayBuffer(file);

    }, onErrorReadFile);
}

but, I couldn't succeed to use it (or to embed it in my code), anyone know how can I load back an image I stored and push it in to my ionic code:

<img [src]="avatar" style="margin: auto;" alt="Profile">
this.avatar = "???";

Thank you!!

Upvotes: 2

Views: 8981

Answers (2)

TizonDife Villiard
TizonDife Villiard

Reputation: 923

Here is an example:

1.Download the image from this URL http://s14.postimg.org/i8qvaxyup/bitcoin1.jpg

 download() {
   var fileTransfer = new Transfer();
   var url = encodeURI("http://s14.postimg.org/i8qvaxyup/bitcoin1.jpg");
   var fileName = "bitcoin.jpg";
   fileTransfer.download(url, cordova.file.dataDirectory + fileName)
     .then((entry)=>{
       console.log('download complete: ' + entry.toURL());
     }, (error) => {
       console.log("error", "Error file transfert");
  });
 }

To test if the file was downloaded, run in your terminal:

 adb shell
 run-as com.package.name
 cd files
 ls

2.Upload the image

It is very simple to load the file. Declare a variable in your class

myImg: any;

And write the methode to upload the image (trivial):

 upload(){
   var temp = "bitcoin.jpg";
   this.myImg = cordova.file.dataDirectory + temp;
 }  

Load the image:

<div>
  <img [src]="myImg"/>
</div>

And you can call these methods like that:

initializeApp() {
  this.platform.ready().then(() => {
   this.download();
   this.upload();
   ...
});

}

I hope this will help you !

Upvotes: 2

Eran Levi
Eran Levi

Reputation: 363

Ok, I have found better implementation for this issue, since Ionic2 can save strings directly to the server, so you can easily convert it to Base64 and then save to local storage, here is the result:

getImageBase64String(url: string) {
return new Promise( (resolve, reject) => {

  // Convert image to base64 string
  var canvas = document.createElement('CANVAS'),
    ctx = canvas.getContext('2d'),
    img = new Image;

  img.crossOrigin = 'Anonymous';

  img.onload = () => {
    var dataURL: any = null;
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img, 0, 0);

    // set image quality
    dataURL = canvas.toDataURL('image/jpeg', 0.9);
    canvas = null;
    resolve(dataURL);
  };

  img.onerror = (err) => {
    reject(err);
  };

  img.src = url;
});

}

then

this.getImageBase64String(this.img).then(
          (image: string) => {
            //Use it to save it
          }
      );

Enjoy.

Upvotes: 1

Related Questions