Ionic2:使用 cordova-file-transfer 将图像加载和保存到设备

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

我正在使用 Ionic2 开发应用程序,我正在使用“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);
            }
        );
      });
    }

它运行完美(图像保存在设备上),问题是,我需要在我的应用程序中加载这张图像(我存储在我的设备中)。

我在这个 cordova 库中看到了以下代码:

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);
}

但是,我无法成功使用它(或将其嵌入我的代码中),任何人都知道如何加载我存储的图像并将其推送到我的离子代码中:

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

谢谢!!

好的,这个问题我找到了更好的实现方式,因为Ionic2可以将字符串直接保存到服务器,所以你可以很方便的将它转换成Base64再保存到本地,结果如下:

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;
});

}

然后

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

尽情享受吧。

这是一个例子:

1.Download 图片来自此 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");
  });
 }

要测试文件是否已下载,运行 在您的终端中:

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

2.Upload 图片

加载文件非常简单。在 class

中声明一个变量

myImg: any;

并编写上传图片的方法(简单):

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

加载图像:

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

您可以这样调用这些方法:

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

}

希望对您有所帮助!