我正在研究Ionic 2的项目,我想上传相机拍摄的图像。但是,我无法让它发挥作用。
我正在使用两个插件:
编辑:我收到错误代码1,表示无法从文件传输插件找到文件
我已尝试使用this.camera.DestinationType.FILE_URI
this.fileURL
,但仍然发现文件未找到错误。
我的代码如下。任何建议或意见将不胜感激!
/* Take a picture with camera */
takePicture() {
this.camera.getPicture({
destinationType: this.camera.DestinationType.DATA_URL,
sourceType: this.camera.PictureSourceType.CAMERA,
mediaType: this.camera.MediaType.PICTURE,
encodingType: this.camera.EncodingType.JPEG,
correctOrientation: true
}).then((imageData) => {
// imageData is a base64 encoded string
this.base64Image = "data:image/jpeg;base64," + imageData;
this.fileURL = imageData;
this.images.push(this.base64Image);
this.isPicture = 1;
this.uploadPictures(this.fileURL);
}, (err) => {
console.log(err);
});
}
/* Upload an image */
var fileTransfer: TransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: "images",
fileName: fileURL.substr(fileURL.lastIndexOf('/') + 1),
chunkedMode: true,
mimeType: "image/jpeg",
httpMethod: "POST",
};
this.loading = this.loadingCtrl.create({
content: 'Uploading...',
});
fileTransfer.upload(fileURL, encodeURI(this.API_URL+"api/order/receipt_pic/1491378111.3477"), options).then(data => {
console.log('uploaded');
}, err => {
console.log('upload fail');
console.log(err.code);
});
}
答案 0 :(得分:0)
Data_URL在应用程序上非常繁重,如果图像分辨率很高,可能会导致崩溃。
我的一个工作示例:
捕捉图片:
var cameraOptions = {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation: true
};
navigator.camera.getPicture(
function cameraSuccess(imageUri) {
uploadProfilePicture(imageUri)
.then(function(data){
},function(error){
console.log('failed', error);
});
}, function cameraError(error) {
console.log('error', error);
}, cameraOptions);
uploadProfilePicture(imageUri):
var url = BASE_URL+'/upload-avatar';
var token = AuthService.getAccessToken();
var options = {
fileKey : "image", //this is the name of the param the server is expecting
httpMethod: "POST",
chunkedMode : true,
mimeType : "image/jpeg",
headers : {
'Accept': 'application/json', //this is important
'Authorization': token
}
};
var ft = new FileTransfer();
ft.upload(imageUri, encodeURI(url), win, fail, options);
function win (){
}
function fail (){
}
由于您使用httpMethod: "POST"
,因此需要将headers
附加到选项对象。
'Accept': 'application/json'
对我有用,我也发送令牌,因为用户必须通过身份验证才能上传图片。