无法从Ionic Camera将图像上传到AWS S3?

时间:2015-11-02 20:33:46

标签: angularjs cordova amazon-s3 ionic

我正在尝试使用Ionic将图像上传到AWS,但存储在AWS中的文件出错,我看不到图像。错误说明:图像...无法显示,因为它包含错误。这是代码:

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 个答案:

答案 0 :(得分:4)

我最终从getPicture返回的base64编码图像创建了一个BLOB。

   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)...

答案 1 :(得分:0)

这是我的代码。 首先,我将imageURL转换为可以从Camera或Photolibrary获取的FILE类型。 然后我尝试将图像上传到AWS s3存储桶。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:background="@color/background"
    tools:context=".home.LoginActivity">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp">

        <ImageView
            android:id="@+id/log_in_launcher_icon"
            android:layout_width="110dp"
            android:layout_height="110dp"
            android:layout_centerHorizontal="true"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_launcher_logo" />

        <RelativeLayout
            android:id="@+id/log_in_rellay1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/log_in_launcher_icon"
            >


            <LinearLayout
                android:id="@+id/log_in_linlay1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/roboto_light"
                        android:text="@string/email_title"
                        android:textColor="@color/dirtyWhite"
                        android:textSize="15sp" />

                    <EditText
                        android:id="@+id/log_in_et_email"
                        android:layout_width="match_parent"
                        android:layout_height="40dp"
                        android:background="@drawable/et_bg"
                        android:inputType="textEmailAddress"
                        android:fontFamily="@font/roboto_light"
                        android:paddingEnd="15dp"
                        android:paddingStart="15dp"
                        android:textColor="@color/dirtyWhite"
                        android:textSize="15sp"
                        android:nextFocusForward="@+id/log_in_et_password"/>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/roboto_light"
                        android:text="@string/password_title"
                        android:textColor="@color/dirtyWhite"
                        android:textSize="15sp" />

                    <EditText
                        android:id="@+id/log_in_et_password"
                        android:layout_width="match_parent"
                        android:layout_height="40dp"
                        android:background="@drawable/et_bg"
                        android:inputType="textPassword"
                        android:fontFamily="@font/roboto_light"
                        android:paddingEnd="15dp"
                        android:paddingStart="15dp"
                        android:textColor="@color/dirtyWhite"
                        android:textSize="15sp" />

                </LinearLayout>

            </LinearLayout>

            <ProgressBar
                android:id="@+id/log_in_pb"
                style="?android:attr/progressBarStyle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/log_in_linlay1"
                android:layout_centerHorizontal="true"
                android:visibility="gone"/>

            <Button
                android:id="@+id/log_in_btn_log_in"
                android:layout_width="wrap_content"
                android:layout_height="40dp"
                android:layout_below="@+id/log_in_linlay1"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="50dp"
                android:background="@drawable/btn_bg"
                android:fontFamily="@font/roboto_light"
                android:paddingEnd="70dp"
                android:paddingStart="70dp"
                android:text="@string/log_in_title"
                android:textColor="@color/dirtyWhite"
                android:textSize="16sp" />

        </RelativeLayout>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/log_in_rellay2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="20dp"
        >

        <Button
            android:id="@+id/log_in_btn_sign_up"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/transparent"
            android:fontFamily="@font/roboto_light"
            android:text="@string/log_in_sign_up"
            android:textAllCaps="true"
            android:textColor="@color/dirtyWhite"
            android:textSize="16sp" />

        <Button
            android:id="@+id/log_in_btn_forgot_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:background="@color/transparent"
            android:fontFamily="@font/roboto_light"
            android:text="@string/log_in_forgot_password"
            android:textAllCaps="true"
            android:textColor="@color/dirtyWhite"
            android:textSize="16sp" />

    </RelativeLayout>

</RelativeLayout>

};

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});

}

如有任何疑问,请告诉我