离子相机上传到S3

时间:2018-04-01 17:13:08

标签: ionic-framework amazon-s3 ionic3

在使用FILE_URI作为camera.DestinationType时,我在拍照并将其上传到S3存储桶时遇到问题。当使用与DATA_URL DestinationType相同的过程时,它可以正常工作。

使用FILE_URI时,上传到S3存储桶的文件说它已损坏。我注意到文件大小比实际图像小得多(~100B)。

以下是我使用的版本: Ionic Framework 3.9.2和cordova-plugin-camera 4.0.2

以下是我使用的代码:

const options: CameraOptions = {
 quality: 100,
 correctOrientation: true,
 destinationType: this.camera.DestinationType.FILE_URI,
 encodingType: this.camera.EncodingType.JPEG,
 mediaType: this.camera.MediaType.PICTURE,
 sourceType: this.camera.PictureSourceType.CAMERA,
}

this.camera.getPicture(options).then((imageData) => {

 console.log(imageData);

 let base64data = 'data:image/jpeg;base64,' + imageData;
 this.bigImg = base64data;
 // imageData is either a base64 encoded string or a file URI
 // If it's base64:
 this.selectedPhoto = this.dataURItoBlob(this.bigImg);
}, (err) => {
 // Handle error
 console.log("Get Image Error: " + err);
});

this.sub = AWS.config.credentials.identityId;
let uploadMessage = "Uploading Image...";
let photoName = "testPic";
this.upload(this.selectedPhoto, uploadMessage, photoName)
.then(data => {
   // Change active page to list
   this.navCtrl.setRoot(TabsPage).then(() => {
  });
});

dataURItoBlob(dataURI) {
 // code adapted from: http://stackoverflow.com/questions/33486352/cant-upload-image-to-aws-s3-from-ionic-camera
 let binary = atob(dataURI.split(',')[1]);
 let array = [];
 for (let i = 0; i < binary.length; i++) {
   array.push(binary.charCodeAt(i));
 }
 return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
};

upload(selectedPhoto, uploadMessage, photoName) {
 return new Promise((resolve, reject) => {
  let loading = this.loadingCtrl.create({
    content: uploadMessage
  });
  loading.present();

  if (selectedPhoto) {
    this.s3.upload({
      'Key': 'protected/' + this.sub + '/' + photoName,
      'Body': selectedPhoto,
      'ContentType': 'image/jpeg'
    }).promise().then((data) => {
      this.data2 = data;
      console.log('upload complete:', JSON.stringify(data));
      loading.dismiss();

      resolve(data);
    }, err => {
      console.log('upload failed....', JSON.stringify(err));
      loading.dismiss();

      reject(err);
    });
  } else {
    loading.dismiss();

    reject("upload failed");
  }
});

0 个答案:

没有答案