download method
void
download({})
下载文件,由于web端适配问题,没有通过Future的方式
Implementation
void download({
required String urlPath,
required String filename,
Map<String, dynamic>? params,
Map<String, dynamic>? body,
Options? options,
CancelToken? cancelToken,
ProgressCallback? onProgress,
OnSuccess<File?>? onSuccess,
OnFailed? onFailed,
}) async {
if (isWeb()) {
var uaType = await DeviceUtil.getUaType();
if (!uaType.isWeb) {
var success = await urlPath.launch();
if (success) {
onSuccess?.call(null);
} else {
onFailed?.call(CstException.buildException("Url launch 失败"));
}
} else {
// 如果是Web端,通过js交互实现。注意,需要将index.html下的<script>代码复制到自己项目指定位置
// Web端需要单独处理是因为dio的下载不支持Web端
webOnProgress(progress, total) {
if (onProgress != null) {
onProgress(progress, total);
}
}
webOnSuccess() {
if (onSuccess != null) {
onSuccess(null);
}
}
webOnFailed(e) {
if (onFailed != null) {
onFailed(CstException(-1, e.toString()));
}
}
js.context.callMethod('download',
[urlPath, filename, webOnProgress, webOnSuccess, webOnFailed]);
}
} else {
var targetFile = await getDownloadPath(filename: filename);
try {
// 其他端使用dio的下载
await _dio.download(urlPath, targetFile.path,
queryParameters: params,
data: body,
options: options,
deleteOnError: true,
lengthHeader: Headers.contentLengthHeader,
cancelToken: cancelToken, onReceiveProgress: (progress, total) {
if (onProgress != null) {
onProgress(progress, total);
}
if (cancelToken?.isCancelled == true && onFailed != null) {
onFailed(CstException(-1, "下载已取消"));
}
if (cancelToken?.isCancelled == false &&
total != -1 &&
progress >= total &&
onSuccess != null) {
onSuccess(targetFile);
}
});
} catch (e) {
if (onFailed != null) {
String? detailMessage;
if (e is Error) {
detailMessage = e.stackTrace?.toString();
} else {
detailMessage = e.toString();
}
onFailed(CstException(-1, "下载失败", detailMessage: detailMessage));
}
}
}
}