将单个图片上传到我的api时遇到一个小问题。 api端点完成后只需要一张图片。
我在项目中使用cordova相机插件拍照。它返回bas64。 我找到了一种方法,将其转换为jpg,代码如下
$scope.picture = 'data:image/jpeg;base64,' + data;
var blob = new Blob([$scope.picture], {type: 'image/png'});
var picture = new File([blob], 'picture.jpg');
在我转换它之后(我假设有效)我从角度使用以下代码获得正常的http指令。
$http({
method: 'POST',
url: '/me/saveavatar',
headers: {
'Content-Type': undefined
},
data: {
photo: picture
}
})
.success(function (data) {
console.log("success" + data);
})
.error(function (response) {
console.log("error" + response);
});
但我没有将我的文件上传到服务器。如果它是第一个文件。我错过了什么?
完整的功能如下:
$scope.takePicture = function(){
var options = {
//these are option that are passed to the function so we can grab the picture and zise it the way we want.
destinationType: Camera.DestinationType.DATA_URL,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 250,
targetHeight: 500,
allowEdit : true,
quality:100
};
//the plugin is calling upon the camera the plugin is called cordovaCamera
$cordovaCamera.getPicture(options).then(function(data) {
//succes handeling
$scope.picture = 'data:image/jpeg;base64,' + data;
var blob = new Blob([$scope.picture], {type: 'image/png'});
var picture = new File([blob], 'picture.jpg');
//uploading the picture
console.log(picture);
$http({
method: 'POST',
url: '/me/saveavatar',
headers: {
'Content-Type': undefined
},
data: {
photo: picture
}
})
.success(function (response) {
console.log("success" + response);
})
.error(function (response) {
console.log("error" + response);
});
},
// Error handeling
function(){
var alertPopup = $ionicPopup.alert({
title: 'Camera afgesloten?',
template: 'U kunt altijd nog een foto maken!'
});
});
};