首页 文章

Ionic 3使用额外数据上传多个图像

提问于
浏览
0

我有一个离子3应用程序;我正在处理上传 Profiles 图片功能 . 在这里,我想使用相机从图库或捕获图像中选择图像 . 之后,我将有两个images / image_paths . 我想上传这两个图像以及user_id,access_token

选择图像从图库中选择= { Headers :'选择图片',消息:'选择最少1张图片',maximumImagesCount:1,outType:0};

this.imagePicker.getPictures(option).then(results => {
          for (var i = 0; i < results.length; i++) {
            // alert('Image URI: ' + results[i]);
            this.imageSelected = "data:image/jpeg;base64," +results[i];
            // this.imageSelected = results[i];
            let option = {
              quality: 100,
              targetHeight: 400,
              targetWidth: 400,
            };
            this.crop.crop(this.imageSelected, option).then((data) => {
              this.imageCropped = "data:image/jpeg;base64," +data;
              // alert(this.imageCropped);
              this.saveProfileImage(this.imageSelected, this.imageCropped);
            }, err => {
              this.imageCropped = '';
              alert(err);
            });
          }
        }, err => {
          this.imageSelected = '';
          alert('Error' + err);
        })

从相机选择一个图像让选项:CameraOptions = {quality:100,destinationType:this.camera.DestinationType.DATA_URL,encodingType:this.camera.EncodingType.JPEG,mediaType:this.camera.MediaType.PICTURE}

this.camera.getPicture(options).then((imageData) => {
          // alert(imageData);
          this.imageSelected = "data:image/jpeg;base64," +imageData;
          let option = {
            quality: 100,
            targetHeight: 400,
            targetWidth: 400,
          };
          this.crop.crop(this.imageSelected, option).then((data) => {
            this.imageCropped = "data:image/jpeg;base64," +data;
            this.saveProfileImage(this.imageSelected, this.imageCropped);
          }, err => {
            this.imageCropped = '';
            alert(err);
          });
        }, (err) => {
          this.imageSelected = '';
          alert('Error' + err);
        });

请参阅上面的代码,如果它是正确的,建议我如何使用表单数据或任何其他方法编写上传功能

这是我尝试上传图片的第一种方式的屏幕截图
![][1]

This is a screenshot of the second way I tried uploading images

2 回答

  • 1

    即使我在一段时间后面临同样的问题,也没有在网上找到适当的解决方案 . 下面是解决方案,我在一些研究后发现并且工作得非常好,不仅适用于图像,还适用于其他文件 . 既然问题是关于图像,我将解释图像的答案w.r.t . (除了选择文件之外,其他文件的过程保持不变) .

    • 您可以使用Cordova camera plugin选择图像,安装插件并将其导入app.module.ts并将其添加到提供商后,您可以使用以下代码从相机或图库中选择图像 . ActionSheetController将是为用户提供选项,从图库或相机中选择图像的最佳方式 .

    从相机中选择图像的代码:

    const options: CameraOptions = {
      quality: 100,
      correctOrientation: true,
      cameraDirection: 1,
    }
    
    this.camera.getPicture(options).then((imageData) => {
      console.log("IMAGE DATA IS", imageData);
    }).catch(e => {
      console.log("Error while picking from camera", e)
    })
    

    从库中选择图像的代码:

    var options = {
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.FILE_URI,
    };
    this.camera.getPicture(options).then((imageData) => {
      console.log("IMAGE DATA IS", imageData);
    }).catch(e => {
      console.log("Error while picking from gallery", e)
    });
    
    • 选择图像后,需要使用com-badrit-base64插件将其转换为base64 . 安装插件并将其导入app.module.ts并添加到提供者列表后,只需将相机插件的输出传递给此,所选图像将转换为base64 .

    下面是将所选图像转换为base64的代码片段,我已经为相机编写了它,它对于图库来说仍然是相同的 . 将图像转换为base64后,将其推送到数组 . 现在,您可以选择多个图像并将其值存储在数组中 .

    var options = {
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.FILE_URI,
    };
    this.camera.getPicture(options).then((imageData) => {
      console.log("IMAGE DATA IS", imageData);
    
      let filePath: string =imageData
        this.base64.encodeFile(filePath).then((base64File: string) => {
        console.log(base64File);
          this.base64File.push(base64File);
        }, (err) => {
        console.log(err);
        });
    
    }).catch(e => {
      console.log("Error while picking from gallery", e)
    });
    
    • 现在通过API将数据发送到服务器 . 您可以使用cordova-plugin-advanced-http或Angular-http来实现它 . API应该采用数组格式的图像以及其他参数 . 由于base64图像将是一个长度更大的字符串,因此建议使用url编码格式的formData或row,以用于REST的post方法 .

    • 现在在后端,将解析正文并提取图像数组 . 在用于编写API的所有流行的后端语言(Java,PHP,NodeJS,C#等)中,有一些免费库可以将base64图像转换为实际图像 .

    • Whola,就是这样,现在您可以通过API将多个图像发送到您的服务器 . 除了图像,如果您尝试选择任何其他MIME类型的文件(pdf,doc,docx等),您可以使用相同的方法 .

    我还在以下位置创建了一个git hub存储库:https://github.com/coolvasanth/upload-multiple-image-files-in-Ionic-3-4/blob/master/README.md

  • 1

    首先,您需要创建一个 formData object .

    private formData:any = {
        'user_id':this.userId,
        'access_token':this.accessToken,
        'device_id':this.devId,
        'device_type':this.devType,
        'registration_ip':this.ipAdd,
        'image':'',
        'crop_image'
      };
    

    Need to change imagePicker

    this.imagePicker.getPictures(option).then(results => {
    
      for (var i = 0; i < results.length; i++) {
        // alert('Image URI: ' + results[i]);
    
        //set it results[i] in unCropImages
    
        this.data.image= "data:image/jpeg;base64," +results[i];
    
        this.imageSelected = results[i];
        let option = {
          quality: 100,
          targetHeight: 400,
          targetWidth: 400,
        };
    
        this.crop.crop(this.imageSelected, option).then((data) => {
          this.imageCropped = "data:image/jpeg;base64," +data;
          // alert(this.imageCropped);
    
          //set it imageCropped in cropImage
    
          this.data.crop_image= this.imageCropped;
    
          //No need to this function
    
          this.saveProfileImage();
    
        }, err => {
          this.imageCropped = '';
          alert(err);
        });
      }
    }, err => {
      this.imageSelected = '';
      alert('Error' + err);
    })
    

    Need to change in camera

    this.camera.getPicture(options).then((imageData) => {
              // alert(imageData);
              this.imageSelected = "data:image/jpeg;base64," +imageData;
    
              this.data.image= "data:image/jpeg;base64," +results[i];
    
              let option = {
                quality: 100,
                targetHeight: 400,
                targetWidth: 400,
              };
              this.crop.crop(this.imageSelected, option).then((data) => {
                this.imageCropped = "data:image/jpeg;base64," +data;
    
                this.data.crop_image= this.imageCropped;
    
              this.saveProfileImage();
              }, err => {
                this.imageCropped = '';
                alert(err);
              });
            }, (err) => {
              this.imageSelected = '';
              alert('Error' + err);
            });
    

    Setup POST method

    First of all you need to inject HttpClientModule in import section of app.module.ts file

    Then inject private http: HttpClient inside constructor in saveProfileImage() funtion class

    change in saveProfileImage()

    saveProfileImage(){
    
      return new Promise((resolve, reject) => {
        this.http.post('Your URL', JSON.stringify(this.formData))
          .subscribe(res => {
            resolve(res);
           //success 
          }, (err) => {
            reject(err);
            //fail
          });
      });
    
    }
    

相关问题