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

I'm working on app in Ionic2 and I'm downloading an image using "cordova-plugin-file-tra

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!!

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!!

Share Improve this question edited Jun 18, 2016 at 4:17 Hardik Vaghani 2,17327 silver badges47 bronze badges asked Jun 17, 2016 at 20:48 Eran LeviEran Levi 3631 gold badge9 silver badges22 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 2

Here is an example:

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

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

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

 adb shell
 run-as .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 !

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745316100a4622226.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信