【问题标题】:Issue with ionic 3 movefile functionionic 3 movefile函数的问题
【发布时间】:2019-02-20 15:56:02
【问题描述】:

我正在尝试使用文件原生插件提供的 moveFile 功能,我无法上传屏幕截图,因为它是属于我公司的私人项目,但我会尽量解释 我使用相机本机插件拍照,相机工作得很好并且照片正在显示,但是当我尝试使用文件本机插件(moveFile)方法只是将拍摄的照片移动到文件目录而不是缓存时,什么也没有发生! 页面TS中导入file和fileError,App Module中也提供了file

这是我的 TS(更新):

getImageFromCamera() {
const options: CameraOptions = {
  quality: 20,
  saveToPhotoAlbum: true,
  destinationType: this.camera.DestinationType.FILE_URI,
  sourceType: this.camera.PictureSourceType.CAMERA,
  encodingType: this.camera.EncodingType.JPEG,
  allowEdit: true
};
this.camera.getPicture(options).then((imageData) => {
  this.imageUrl = imageData;
  let imageName = imageData.substr(imageData.lastIndexOf('/') + 1);
  this.file.checkDir(this.file.externalRootDirectory, 'DEMO')
    .then(() => {
      this.fileCreated = true;
    }, (err) => {
    });
  if (this.fileCreated) {
  }
  else {
    this.file.createDir(this.file.externalRootDirectory, "DEMO", true)
      .then((res) => {
      }, (err) => {
      });
  }
  let tempPath = this.imageUrl.substr(0, this.imageUrl.lastIndexOf('/') +1);
  let androidPath = this.file.externalRootDirectory + '/DEMO/';
  this.file.moveFile(tempPath, imageName, androidPath, imageName)
    .then((res) => {
      this.file.readAsDataURL(androidPath, imageName)
        .then((res) => {
          this.images.push(res);
        }, (err) => {
          console.log("Error in Image Get Path---");
          console.log(JSON.stringify(err));
        });
    }, (err) => {
    });
  // this.toDataURL(this.imageUrl, function (dataUrl) {
  //  console.log('RESULT:' + dataUrl);
  //  this.images.push(this.imageUrl);
  // });
 }, (err) => {
  console.log(JSON.stringify(err));
 });
}
toDataURL(url, callback) {
let xhr = new XMLHttpRequest();
xhr.onload = function () {
  let reader = new FileReader();
  reader.onloadend = function () {
    callback(reader.result);
  };
  reader.readAsDataURL(xhr.response);
 };
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}

我的 HTML

<ion-item>
  <h5>Choose files to upload</h5>
  <button (tap)="getImageFromCamera()" item-end ion-button round outline 
   color="sideBar">Upload</button>
</ion-item>
<ion-slides *ngIf="images.length >= 1">
  <ion-slide style="float: left;" *ngFor="let image of images; let i = 
   index;" class="image-container">
    <ion-icon (tap)="onDeletePhoto(i)" class="icon-container" name="close- 
     circle"></ion-icon>
    <img [src]="image" width="100">
  </ion-slide>
</ion-slides>
<ion-item>

如您所见,我尝试使用 photoError 字符串查看屏幕上的 4 个参数,一切看起来都很好,旧路径正确,名称、新路径和新名称正确,但图像没有从图片文件夹中移动,我发现我手机上的文件夹是空的,图片还在图片文件夹中,当我尝试设置时,imageUrl 字符串也显示了图片的正确路径(新路径) imageUrl 到旧路径,也没有显示图像,我在另一台 Android 设备上尝试了该应用程序,也是同样的问题,所以它不是来自我的手机。

有人知道吗?如果您有任何我没有提供答案的问题,请随时提出。

【问题讨论】:

    标签: typescript file ionic-framework ionic3 ionic-native


    【解决方案1】:

    参考此代码,我已使用此代码将图像移动到指定文件夹。跳这会对你有所帮助..
    这是我的代码:

      getImageFromCamera() {
    
        const options: CameraOptions = {
            quality: 20,
            saveToPhotoAlbum: true,
            destinationType: this.camera.DestinationType.FILE_URI,
            sourceType: this.camera.PictureSourceType.CAMERA,
            encodingType: this.camera.EncodingType.JPEG,
            allowEdit: true
        };
    
        this.camera.getPicture(options).then((imageData) => {
    
            this.imageURI = imageData;
            this.imageName = imageData.substr(imageData.lastIndexOf('/') + 1);
    
            // Create a folder 'DEMO' in memory location of device to store image
    
            this.file.checkDir(this.file.externalRootDirectory, 'DEMO')
                .then(() => {
                    this.fileCreated = true;
                }, (err) => {
                    console.log("checkDir: Error");
                });
            if (this.fileCreated) {
                this.presentToast("Directory Already exist");
            }
            else {
                this.file.createDir(this.file.externalRootDirectory, "DEMO", true)
                    .then((res) => {
                        this.presentToast("Directory Created");
                    }, (err) => {
                        console.log("Directory Creation Error:");
                    });
            }
    
            //FILE MOVE CODE
    
            let tempPath = this.imageURI.substr(0, this.imageURI.lastIndexOf('/') + 1);
            let androidPath = this.file.externalRootDirectory + '/DEMO/';
    
            this.file.moveFile(tempPath, this.imageName, androidPath, this.imageName)
                .then((res) => {
                    this.presentToast("Image Moved Successfully");
    
                }, (err) => {
                    this.presentToast("Image Moved Failed");
                });
            //Complete File Move Code
    
            this.toDataURL(this.imageURI, function (dataUrl) {
                console.log('RESULT:' + dataUrl);
            });
        }, (err) => {
            console.log(JSON.stringify(err));
        });
    
    }
     toDataURL(url, callback) {
        let xhr = new XMLHttpRequest();
        xhr.onload = function () {
            let reader = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            };
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    }
    

    【讨论】:

    • 感谢您的回复,我会尝试更新您。
    • 谢谢,它比我的代码好,它创建目录并将照片移动到它,但问题是当我尝试在 html 上显示照片时,我什么都看不到,我试过了要查看 img 标签中的路径,它是正确的,如果我尝试显示项目资产文件夹中的图像,它会显示,但从拍摄的图像中它不起作用,你知道为什么会这样吗?我的 HTML 仍然与问题中提到的相同
    • 发生这种情况是因为您不能直接从本地路径显示图像,而是必须先从本地路径(android 设备的路径)读取该图像,将结果存储在变量中,然后将该变量分配给 .. 我也这样做了,我正在与你分享我的代码。跳这对你有帮助。
    【解决方案2】:

    这里我为你创建了 Demo,这段代码从相机拍摄照片并保存到文件夹中,然后从本地路径读取该图像并显示在屏幕上,我也测试过,对我来说很好,现在应该很好用.

    Home.ts

    确保您已导入所有包

    从'@angular/core'导入{组件};
    从 'ionic-angular' 导入 { NavController, ToastController };
    从“@ionic-native/camera”导入{Camera, CameraOptions};
    从 '@ionic-native/file' 导入 {File};

    export class HomePage {
    
    public imageURI: any;
    public imageName: any;
    public fileCreated: boolean = false;
    public imageString: any;
    resultImageArray: any;
    

    构造函数(公共 navCtrl:NavController, 私人文件:文件, 私人相机:相机, 私人 toastCtrl: ToastController,) {

    }

    getImageFromCamera() {
    
    
        const options: CameraOptions = {
            quality: 20,
            saveToPhotoAlbum: true,
            destinationType: this.camera.DestinationType.FILE_URI,
            sourceType: this.camera.PictureSourceType.CAMERA,
            encodingType: this.camera.EncodingType.JPEG,
            allowEdit: true
        };
    
        this.camera.getPicture(options).then((imageData) => {
            this.imageURI = imageData;
            this.imageName = imageData.substr(imageData.lastIndexOf('/') + 1);
    
            // Create a folder in memory location
            this.file.checkDir(this.file.externalRootDirectory, 'ImagesDemo')
                .then(() => {
                    this.fileCreated = true;
                }, (err) => {
                    console.log("checkDir: Error");
                    console.log(JSON.stringify(err));
                    this.presentToast("checkDir Failed");
                });
            if (this.fileCreated) {
                this.presentToast("Directory Already exist");
            }
            else {
                this.file.createDir(this.file.externalRootDirectory, "ImagesDemo", true)
                    .then((res) => {
                        this.presentToast("Directory Created");
                    }, (err) => {
                        console.log("Directory Creation Error:");
                        console.log(JSON.stringify(err));
                    });
            }
    
            //FILE MOVE CODE
            let tempPath = this.imageURI.substr(0, this.imageURI.lastIndexOf('/') + 1);
            let androidPath = this.file.externalRootDirectory + '/ImagesDemo/';
            this.imageString = androidPath + this.imageName;
    
            this.file.moveFile(tempPath, this.imageName, androidPath, this.imageName)
                .then((res) => {
                    this.presentToast("Image Saved Successfully");
                    this.readImage(this.imageString);
    
                }, (err) => {
                    console.log("Image Copy Failed");
                    console.log(JSON.stringify(err));
                    this.presentToast("Image Copy Failed");
                });
            //Complete File Move Code
    
            this.toDataURL(this.imageURI, function (dataUrl) {
                console.log('RESULT:' + dataUrl);
            });
        }, (err) => {
            console.log(JSON.stringify(err));
            this.presentToast(JSON.stringify(err));
        });
    }
    
    
    presentToast(msg) {
        let toast = this.toastCtrl.create({
            message: msg,
            duration: 2000
        });
        toast.present();
    }
    
    toDataURL(url, callback) {
        let xhr = new XMLHttpRequest();
        xhr.onload = function () {
            let reader = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            };
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    }
    
    
    
    readImage(filePath) {
        let tempPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
        let imageName = filePath.substr(filePath.lastIndexOf('/') + 1);
    
        this.file.readAsDataURL(tempPath, imageName)
            .then((res) => {
                this.presentToast("Image Get Done");
                this.resultImageArray = res;
            }, (err) => {
                this.presentToast("Image Get Error");
            });
    }
    

    }

    Home.html

     <button ion-button   item-end icon-start block  (click)="getImageFromCamera()">Click Here</button>
    
    
      <ion-card *ngIf=resultImageArray>
    <img src="{{resultImageArray}}"/></ion-card>
    

    现在我们准备好了,只要运行到设备,你就会得到你想要的输出。

    我还附上了我的代码输出。

    【讨论】:

    • 是的,它现在显示一个数据 url,但没有图像,只显示损坏的图像小图标
    • 这个图标需要很长时间才能生成base64数据url
    • 你能分享你的代码吗?所以我可以找出问题所在..!
    • 我评论了之前的函数 this.toDataUrl 因为我现在使用的是你提供的最后一个函数
    • 我已经编辑了我的回复,请查看更新后的回复.. :)
    猜你喜欢
    • 2018-02-09
    • 2018-03-28
    • 2019-04-18
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 2019-06-23
    相关资源
    最近更新 更多