使用cordova的camera.getPicture将图像上传到Parse时遇到问题

时间:2014-01-23 05:49:24

标签: cordova parse-platform

我正在尝试使用Cordova的camera.getPicture方法将图像保存到Parse。

以下是运行此代码的示例代码:

// onclick event to take a picture
<button onclick="capturePhoto();"></button>

// function implementation
function capturePhoto() {
    // Take picture using device camera and retrieve image as base64-encoded string
    navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
        destinationType: destinationType.DATA_URL
    });
}

// Success callback
function onPhotoDataSuccess(imageData) {
    var parseFile = new Parse.File("myPic.jpg", {base64:imageData});
    parseFile.save().then(function() {
        // The file has been saved to Parse.                
    }, function(error) {
        // The file either could not be read, or could not be saved to Parse.
    });
}

如果我只是设置一个字符串,如documentation所示,它可以运行JavaScript。

var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
var file = new Parse.File("myfile.txt", { base64: base64 });

有人可以指出我正确的方向或提供替代实施。

谢谢。

2 个答案:

答案 0 :(得分:1)

在发送之前,您仍需要将一些文件信息添加到imageData

var base64pic = "data:image/jpeg;base64," + imageData;
var parseFile = new Parse.File("myPic.jpg", {base64:base64pic});

答案 1 :(得分:0)

您可以使用REST api从cordova app上传文件。

在您的控制器中:

var cameraOptions = {
    destinationType: 0, // base64
    encodingType: 0 
};

$scope.takePicture = function() {
    cameraOptions.sourceType = 1;
    navigator.camera.getPicture(onSuccess, onFail, cameraOptions);
}

$scope.selectPicture = function() {
    cameraOptions.sourceType = 0;
    navigator.camera.getPicture(onSuccess, onFail, cameraOptions);
}

function onSuccess(picture) {

    File.upload(picture)
        .success(function(data) {
            // upload finish
        });

    $scope.$apply(function() {
        $scope.preview = 'data:image/jpeg;base64,' + picture;
    });
}

function onFail(resp) {
    alert('Error: ' + resp);
}

在文件服务中:

angular.factory('File', function ($http) {
    return {
        upload: function (photo) {

            var json = {
                'base64': photo,
                '_ContentType': 'image/jpeg'
            }

            var config = {
                method: 'POST',
                url: 'https://api.parse.com/1/files/pict.jpg',
                data: json,
                headers: {
                    'X-Parse-Application-Id': 'XXXXX',
                    'X-Parse-REST-API-Key': 'XXXXX'
                }
            };

            return $http(config);
        }
    }
});