【问题标题】:Ionic2: Load and Save image to device using cordova-file-transferIonic2:使用cordova-file-transfer将图像加载和保存到设备
【发布时间】:2016-06-17 20:48:23
【问题描述】:

我正在 Ionic2 中开发应用程序,我正在使用“cordova-plugin-file-transfer”下载图像,并使用以下代码感谢 (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);
}

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

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

谢谢!!

【问题讨论】:

    标签: javascript cordova cordova-plugins ionic2


    【解决方案1】:

    这是一个例子:

    1.从此网址下载图片 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.上传图片

    加载文件非常简单。在你的类中声明一个变量

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

    }

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      好的,这个问题我找到了更好的实现,因为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
                }
            );
      

      享受吧。

      【讨论】:

        猜你喜欢
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多