uploadImage<T> method
brief 上传图片 (通过Future方式请求,可以使用await阻塞直到获取到结果) @param url 接口地址 @param filePath 图片地址 @param attachmentType 上传附件类型 @param customAttachmentType 上传附件类型 (attachmentType为custom时,取customAttachmentType的值, 若为空默认为"system") @param fileName 图片名字 @param mime 图片格式 @param showProgress 是否显示上传进度 @param onSendProgress 发送文件进度回调 @param onReceiveProgress 接收文件进度回调 @param cancelToken 取消请求的token @param options 对请求的设置
Implementation
Future<BaseEntity<T>>uploadImage<T>(String url, String filePath, AttachmentType attachmentType, {
String? customAttachmentType,
String? fileName,
String mime = 'png',
bool showProgress = false,
bool isShow = false, // 是否显示加载吐司
ProgressCallback? onSendProgress,
ProgressCallback? onReceiveProgress,
CancelToken? cancelToken,
Options? options
}) async {
assert(!Device.isWeb, "此上传图片方法不适用于web端");
try {
String path = filePath;
String name = fileName ?? DateTime.now().millisecondsSinceEpoch.toString() + Random().nextInt(1000).toString();
String type = (AttachmentType.custom == attachmentType) ? customAttachmentType??'system' : getAttachmentType(attachmentType);
FormData formData = FormData.fromMap({
"file": await MultipartFile.fromFile(path, filename: name),
"type": type
});
bool isToastInit = EasyLoading.instance.overlayEntry != null;
if (isToastInit && isShow) EasyLoading.show();
var response = await _dio.post(url, data: formData, cancelToken: cancelToken, options: options, onReceiveProgress: onReceiveProgress, onSendProgress: (int count, int total) {
if (isToastInit && showProgress && total > 0) {
double progress = count * 1.0/total * 1.0;
EasyLoading.showProgress(progress, status: '${progress.toStringAsFixed(0)}%');
if (progress == 1.0) {
EasyLoading.dismiss(animation: true);
}
}
if (null != onSendProgress) {
onSendProgress(count, total);
}
});
if (isToastInit && isShow) EasyLoading.dismiss();
Map<String, dynamic> _map = await compute(_parseData, response.data.toString());
return BaseEntity.fromJson(_map, isPageData: false);
} catch(e) {
bool isToastInit = EasyLoading.instance.overlayEntry != null;
if (isToastInit && isShow) EasyLoading.dismiss();
if (_isDebugMode && !Device.isWeb) { // debug模式下显示error
showToast('url: $url, code: ${ExceptionHandler.parse_error}, msg: 数据解析错误');
} else {
Log.e('url: $url, exception: $e');
}
return BaseEntity(0, false, ExceptionHandler.parse_error, "数据解析错误", null);
}
}