使用插件:
cordova-plugin-camera
cordova-image-picker
cordova-plugin-file-transfer
- 首先安装三个插件
cordova plugin add cordova-plugin-camera
cordova plugin add cordova-image-picker
cordova plugin add cordova-plugin-file-transfer
需要注意的是,
cordova-plugin-camera
依赖cordova-plugin-compat@1.1.0
,如果项目中已存在更低版本的cordova-plugin-compat
,需要使用cordova plugin remove --force cordova-plugin-compat
强行移除后再安装
- 调取相机方法
takePhoto = () => {
let destinationType = navigator.camera.DestinationType;
let onPhotoDataSuccess = (imageURL) => {
upload(imageURL);
};
let onFail = (message) => {
alert('拍照失败: ' + message);
};
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 90, //图片质量
destinationType: destinationType.FILE_URI
}
);
}
- 调取相册方法
getPhoto = () => {
window.imagePicker.getPictures(
(results) => {
for (let i = 0; i < results.length; i++) {
upload(results[i]);
}
}, (error) => {
alert('Error: ' + error);
}, {
maximumImagesCount: 9, //每次可选择图片数目
quality: 90, //图片质量
outputType: 0
}
);
}
- 上传图片方法
upload = (fileURL) => {
let success = (r) => {
//上传成功, 如果通过相册选择上传,且同事有多张图片,会多次调用此方法
//...
};
let fail = (error) => {
//上传失败
//...
};
let options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.chunkedMode = false;
//options.mimeType = "text/plain";
//上传参数
let params = {};
params.type = 'TEST_IMAGE';
options.params = params;
let ft = new FileTransfer();
//上传地址
let SERVER = FileUploadUrl;
ft.upload(fileURL, encodeURI(SERVER), success, fail, options);
};
以上每种插件都针对不同需求有不同参数,此处就不一一赘述,只是根据实际需求总结的一种上传方法,经过android和IOS手机的测试,仅供参考
网友评论