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



>我试图在使用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.
});
}

如果我只是按照 JavaScript 文档中所示设置一个字符串,它可以工作。

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

有人可以指出我正确的方向或给出替代实现。

谢谢。

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

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

您可以使用 REST API 从 cordova 应用程序上传文件。

在控制器中:

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

最新更新