对象FileTransfert的upload()无法在某些Android设备上运行

时间:2017-12-06 08:34:27

标签: android angularjs cordova typescript ionic3

我开发了一款移动应用来帮助分享内容。用户必须向他发送关于他正在发送的内容的信息,并且他可以添加该对象的图片。所以我使用了cordova文件,相机和fileTransfert插件。它在我测试的大多数设备上运行良好,但我发现在其他手机中,它没有。在对其中一部手机进行一些测试和研究时,我发现用于将图像发送到在线服务器的FileTransfert的upload()方法似乎无法到达存储图像的文件夹。这是我的代码示例。你能帮我确认一下我是否很严格以及如何让这些手机能够在平台上发布图片?

public presentActionSheet(picture) {
 if(this.translateService.currentLang=='fr'){

  let actionSheet = this.actionSheetCtrl.create({
  title: 'Quelle est la source?',
  buttons: [
    {
      icon: 'images',
      text: 'Mon téléphone',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY, picture);
      }
    },
    {
      icon: 'camera',
      text: 'Ma Camera',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.CAMERA, picture);
      }
    },
    {
      text: 'Annuler',
      role: 'cancel'
    }
  ]
});
actionSheet.present();

}else{

  let actionSheet = this.actionSheetCtrl.create({
  title: 'What is the source?',
  buttons: [
    {
      icon: 'images',
      text: 'My Phone',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY, picture);
      }
    },
    {
      icon: 'camera',
      text: 'My Camera',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.CAMERA, picture);
      }
    },
    {
      text: 'Cancel',
      role: 'cancel'
    }
  ]
});
actionSheet.present();

}
  };

  presentToast(message_error) {
  let toast = this.toastCtrl.create({
    message: message_error,
    cssClass: 'alert-box',
    position: 'middle',
    showCloseButton: true,
    closeButtonText: "OK"
  });
   toast.present();
}

//Here is the function to take a picture

public takePicture(sourceType, picture) {
  // Create options for the Camera Dialog
  var options = {
    quality: 100,
    sourceType: sourceType,
    saveToPhotoAlbum: false,
    correctOrientation: true
  };



// Get the data of an image
  this.camera.getPicture(options).then((imagePath) => {
    // Special handling for Android library
    if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
      this.filePath.resolveNativePath(imagePath)
        .then(filePath => {
          let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
          let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
          this.copyFileToLocalDir(correctPath, currentName, this.createFileName(), picture);
        });
    } else {
      console.log('In the else condition');
      var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
      var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
      this.copyFileToLocalDir(correctPath, currentName, this.createFileName(), picture);
    }
  }, (err) => {
    if(this.translateService.currentLang=='fr'){
      this.presentToast('Erreur, pas d\'image selectionnée.');
    }else{
      this.presentToast('Error, no image selected.');
    }
  });
}

  // Create a new name for the image
  private createFileName() {
    var d = new Date(),
    n = d.getTime(),
    newFileName =  n + ".jpg";
    return newFileName;
  }

  // Copy the image to a local folder
  //cordova.file.dataDirectory
  private copyFileToLocalDir(namePath, currentName, newFileName, picture) {
    this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
      if(picture == "imageOne"){
        this.mainImage = newFileName;
      }else if(picture == "imageTwo"){
        this.secondImage = newFileName;
      }else{
        this.thirdImage = newFileName;
      }
      //this.lastImage = newFileName;
    }, error => {
      if(this.translateService.currentLang=='fr'){
        this.presentToast('Erreur, le fichier n\'a pas pu etre sauvegardé.');
      }else{
        this.presentToast('Error, file could not be saved.');
      }
      console.log(error);
    });
  }

  // Always get the accurate path to your apps folder
  public pathForImage(img) {
    if (img === null) {
      return '';
    } else {
      return cordova.file.dataDirectory + img;
    }
  }

  public uploadImage(picture) {
  // Destination URL
  var url = "http://donation.oneclub1.org/donation-new/web/api/upload/image?context=donations";

  // File for Upload
  var targetPath: any;
  if(picture == "imageOne"){
       targetPath = this.pathForImage(this.mainImage);
      }else if(picture == "imageTwo"){
        targetPath = this.pathForImage(this.secondImage);
      }else{
        targetPath = this.pathForImage(this.thirdImage);
      }

  // File name only

  var filename: any;
  if(picture == "imageOne"){
       filename = this.mainImage;
      }else if(picture == "imageTwo"){
        filename = this.secondImage;
      }else{
        filename = this.thirdImage;
      }

  var options = {
    fileKey: "file",
    fileName: filename,
    chunkedMode: false,
    mimeType: "multipart/form-data",
    params : {'fileName': filename}
  };

  const fileTransfer: TransferObject = this.transfer.create();


  // Use the FileTransfer to upload the image
  return fileTransfer.upload(targetPath, url, options);/*.then(data => {
    if(picture == "imageOne"){
       this.mainImageLocal = parseInt(data.response);
      }else if(picture == "imageTwo"){
        this.secondImageLocal = parseInt(data.response);
      }else{
        this.thirdImageLocal = parseInt(data.response);
      }
      //this.presentToast('this is your image id'+this.mainImageLocal);

  }, err => {
    this.loading.dismissAll();
    this.presentToast('Error while uploading file.');
  })*/;

}


  publish(){


  if(this.mainImage!=null){



    this.loading = this.loadingCtrl.create({
    content: this.content2,
    });
    this.loading.present();

     //var categoryId: number;
    for(let parent of this.categories){
      if(parent.name == this.asking_form_group.value.subcategory){
        this.categoryId=parent.id;
        console.log('Id found and it is:'+this.categoryId);
        break;
      };
    };

    //var userId: number;
    if(localStorage.getItem('userId')){
      this.userId= parseInt(localStorage.getItem('userId'));
      console.log('got the user id in nmber:'+this.userId);
    };

    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json' );
    let options = new RequestOptions({ headers: headers });



    this.uploadImage('imageOne').then(data => {

      this.mainImageLocal = parseInt(data.response);

              this.postParams = {
               name: this.asking_form_group.value.name,
               category: this.categoryId,
               description: this.asking_form_group.value.description,
               image: this.mainImageLocal,
               user: this.userId
           }

             this.http.post(this.Api+"/donations/requests?api_key="+localStorage.getItem('userApiKey'), this.postParams, options).map(res => res.json())
              .subscribe(data => {
                 this.loading.dismissAll();
                 if(this.translateService.currentLang=='fr'){
                 this.presentToast('Félicitations!!Votre demande a été postée sur la plateforme!')
                }else{
                  this.presentToast ('Congratulations !! Your request has been posted on the platform!')
                }

                 this.events.publish('ask:posted', 1);
                 this.navCtrl.setRoot(Dashboard);
               }, error => {
                console.log(error);
                //this.asking_form_group.reset();
                this.testor = error.response;
                this.loading.dismissAll();
                this.presentToast(this.error);
              });


    });



  }else{
            this.loading = this.loadingCtrl.create({
            content: this.content2,
            });
            this.loading.present();

            //var categoryId: number;
            for(let parent of this.categories){
              if(parent.name == this.asking_form_group.value.subcategory){
                this.categoryId=parent.id;
                console.log('Id found and it is:'+this.categoryId);
                break;
              };
            };

            if(localStorage.getItem('userId')){
              this.userId= parseInt(localStorage.getItem('userId'));
              console.log('got the user id in nmber:'+this.userId);
            };

            var headers = new Headers();
            headers.append("Accept", 'application/json');
            headers.append('Content-Type', 'application/json' );
            let options = new RequestOptions({ headers: headers });



            this.postParams = {
               name: this.asking_form_group.value.name,
               category: this.categoryId,
               description: this.asking_form_group.value.description,
               image: this.mainImageLocal,
               user: this.userId
           }


             this.http.post(this.Api+"/donations/requests?api_key="+localStorage.getItem('userApiKey'), this.postParams, options).map(res => res.json())
              .subscribe(data => {
                 this.loading.dismissAll();
                 if(this.translateService.currentLang=='fr'){
                 this.presentToast('Félicitations!!Votre demande a été postée sur la plateforme!')
                }else{
                  this.presentToast ('Congratulations !! Your request has been posted on the platform!')
                }
                 this.events.publish('ask:posted', 1);
                 this.navCtrl.setRoot(Dashboard);
               }, error => {
                console.log(error);
                //this.asking_form_group.reset();
                this.testor = error.response;
                this.loading.dismissAll();
                this.presentToast(this.error);
              });

        };

  }

1 个答案:

答案 0 :(得分:0)

对不起,我发现了问题所在,我把它放在这里。问题实际上是关于文件大小的。 Filetransfert默认限制为7.5Mo。发送大于该文件的文件将失败。在某些手机中,相机默认配置将图片尺寸设置为8或更大Mpx。这就是为什么它不适用于那些手机。