对象 FileTransfert 的上传()在某些 android 设备上不起作用

Posted

技术标签:

【中文标题】对象 FileTransfert 的上传()在某些 android 设备上不起作用【英文标题】:upload( ) of object FileTransfert not working on some android devices 【发布时间】:2018-05-20 01:52:43 【问题描述】:

我开发了一个移动应用来帮助分享内容。用户必须提供有关他发送的内容的信息,并且他可以添加对象的图片。所以我使用了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】:

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

【讨论】:

以上是关于对象 FileTransfert 的上传()在某些 android 设备上不起作用的主要内容,如果未能解决你的问题,请参考以下文章

fetch 实现文件上传

如何在typecho中使用腾讯云对象存储cos?

如何在 Azure 数据工厂触发时检查是不是正在上传某些文件(允许在 ADF 中上传时读取文件)

上传图像在某些设备上有效,但返回 Stream FixedLengthSource .inputStream()

我怎样才能在php中上传某些文件类型?

Google Pub/Sub 功能是不是具有在上传后直接通知 Google App Engine 端点的某些功能?