拍照之后 图片上传到oss。
用到了一个插件:image_picker,但是在使用这个插件过程中发现部分安卓手机拍照会奔溃(PlatformException (PlatformException(already_active, Image picker is already active, null, null))),就是运行官方的demo也是一样会报错,版本:0.8.4+3,查了很多资料也没解决,也都尝试了。我们的需求只是拍照上传图片,你可以根据你的需求使用image_picker,他可以选择视频,照片等
拍照代码:
XFile image = await ImagePicker()
.pickImage(source: ImageSource.camera, imageQuality: 60);
上传oss代码:
/*
file 拍照之后的图片文件
uploadIamgeCallBack 上传回调
*/
void uploadImage(XFile file, UploadImageCallBack uploadImageCallBack) async {
if (file == null) return;
String path = file.path;
var name = path.substring(path.lastIndexOf("/") + 1, path.length);
var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
FormData formData = FormData.fromMap({
"image": await MultipartFile.fromFile(path,
filename: name, contentType: MediaType('image', suffix))
});
Dio dio = Dio();
dio.options.headers = {
'BucketName': Api.ossBucketName,// 后台给的桶名
'ObjectDir': Api.ossObjectDir,// 后台给的文件目录名
'Content-Type': 'multipart/form-data'
};
EasyLoading.show(status: '正在上传'); // flutter_easyloading: ^3.0.3
var respone = await dio.post<String>(Api.ossUrl, data: formData);
EasyLoading.dismiss();
if (respone.statusCode == 200) {
String result = respone.data;
Map json = jsonDecode(result);
if (uploadImageCallBack != null) {
uploadImageCallBack(json);
}
}
}