downloadFile method
Future<RxResult<String> >
downloadFile({
- required String savePath,
- ProgressCallback? onReceiveProgress,
下载文件(Future 版本,支持 async/await)
Implementation
// final result = await RxNet.get()
// .setPath("https://example.com/file.zip")
// .downloadFile(savePath: "/path/to/save/file.zip");
// if (result.isSuccess) {
// print("下载成功: ${result.value}");
// }
Future<RxResult<String>> downloadFile({
required String savePath,
adapter.ProgressCallback? onReceiveProgress,
}) async {
if (!(await _checkNetWork())) {
return RxResult.error(NetworkException("Network not available"));
}
final url = _buildFinalUrl();
final payload = _resolveRequestPayload();
final file = File(savePath);
try {
if (!file.parent.existsSync()) {
file.parent.createSync(recursive: true);
}
final adapterRequest = _buildAdapterRequest(
url: url,
queryParams: payload.queryParams,
data: payload.body,
contentType: payload.contentType,
);
final adapter = _requireAdapter();
final response = await adapter.download(
adapterRequest,
savePath,
onProgress: (received, total) {
onReceiveProgress?.call(received, total > 0 ? total : received);
},
);
onResponse?.call(response);
if (response.isSuccess) {
return RxResult(value: savePath, model: SourcesType.net);
} else {
throw NetworkException(
"Download failed with status code ${response.statusCode}", null);
}
} on AdapterException catch (e) {
if (e.type == AdapterExceptionType.cancel) {
throw CancellationException("Download was cancelled", e);
}
throw NetworkException(e.message, e);
} catch (e) {
if (e is RxError) rethrow;
throw NetworkException("Download failed: $e", e);
}
}