Can't upload image to AWS S3 from Ionic Camera

2019-08-11 01:41发布

I'm trying to upload a image to AWS with Ionic but the file stored in AWS have a error and I can't see the image. The error says: The image ... cannot be displayed because it contains errors. This is the code:

var options = {
        quality: 80,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: true,
        encodingType: Camera.EncodingType.JPEG,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true,
        correctOrientation:true
    };
    $cordovaCamera.getPicture(options)
        .then(function(imageData) {
            fileName = "image/image"+$scope.itemsListID;
            function uploadS3(image, name) {
                AWS.config.update({ accessKeyId: "...key...", secretAccessKey: "...key2..." });
                AWS.config.region = 'us-east-1';
                var bucket = new AWS.S3({params: {Bucket: 'bucketname'}});
                var params = {Key: name, ContentType: 'image/jpg', Body: image};
                bucket.upload(params, function(err, data){
                    if(err){
                        //alert("err"); 
                        $ionicPopup.alert({
                            title: "Server Error",
                            content: "Failed to upload the image.",
                            okType: "button-stable"
                        });
                        $ionicLoading.hide();
                    }
                    else{
                        //alert("data");
                        $ionicPopup.alert({
                            title: "Successful",
                            content: "Image have been uploaded successfuly.",
                            okType: "button-stable"
                        });
                        $ionicLoading.hide();
                    }
                });
            }
            uploadS3(imageData, fileName);
        }, function(err) {
            $ionicPopup.alert({
                title: "Server Error",
                content: "Failed to connect with the server.",
                okType: "button-stable"
            });
            console.log(err);
        });

2条回答
beautiful°
2楼-- · 2019-08-11 02:17

here is my code. first I converted imageURL to FILE type that can get from Camera or Photolibrary. then I tried uploading an image to AWS s3 bucket.

var options1 = {
quality: 75,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false

};

$scope.selectPicture = function (option) {
$cordovaCamera.getPicture(option).then(function (imageData) {
  var filename = new Date().getTime() + '.png';
  var imageFile = dataURLtoFile(imageData, filename);
}, function (err) {
});

}

function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(',')
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
    u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});

}

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(',')
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
  }



$scope.uploadImage = function (file) {
var inputConfig = {
  bucket: 'wtcb/ticket',
  access_key: 'AKIAJNHK7O....',
  secret_key: 'XkETf49b/YpM6tgiBRa2x....'
};
AWS.config.update({
  accessKeyId: inputConfig.access_key,
  secretAccessKey: inputConfig.secret_key
});
AWS.config.region = 'us-east-2';
var bucket = new AWS.S3({
  params: {
    Bucket: inputConfig.bucket
  }
});
var params = {
  Key:file.name,
  ContentType: file.type,
  Body: file,
  ACL: 'public-read',
  ServerSideEncryption: 'AES256'
};
bucket.putObject(params, function (err, data) {
  if (err) {} else {
    var object = {
      url: 'https://s3-us-east-2.amazonaws.com/wtcb/ticket/' + filename
    };
  }
})

}

If you have any question, please let me know

查看更多
Root(大扎)
3楼-- · 2019-08-11 02:34

I ended up creating a BLOB from the base64 encoded image returned from getPicture.

   var dataURItoBlob = function(dataURI) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
    };

    //imgData returned from camera getPicture
    var body = dataURItoBlob("data:image/jpeg;base64," + imageData);

    var options = {
              Key: 'mytestimg2.jpg', 
              ContentType: 'image/jpeg', 
              Body:body, 
              ContentEncoding: 'base64'
        }

    //aws specific upload code here
    bucket.upload(options, err, data)...
查看更多
登录 后发表回答