56 lines
1.4 KiB
Dart
56 lines
1.4 KiB
Dart
/// 精选推荐模块
|
|
library;
|
|
import 'dart:io';
|
|
import 'dart:async';
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'package:dio/dio.dart';
|
|
|
|
// 下载管理器类
|
|
class DownloadManager {
|
|
static final Dio _dio = Dio();
|
|
|
|
static Future<String> downloadFile({
|
|
required String url,
|
|
required String fileName,
|
|
required Function(int) onProgress,
|
|
required Function(String) onComplete,
|
|
required Function(String) onError,
|
|
}) async {
|
|
try {
|
|
// 获取存储目录
|
|
Directory directory;
|
|
if (Platform.isAndroid) {
|
|
directory = await getExternalStorageDirectory() ?? await getApplicationDocumentsDirectory();
|
|
} else {
|
|
directory = await getApplicationDocumentsDirectory();
|
|
}
|
|
|
|
String downloadDir = '${directory.path}/Downloads';
|
|
await Directory(downloadDir).create(recursive: true);
|
|
|
|
String safeFileName = _getSafeFileName(fileName);
|
|
String filePath = '$downloadDir/$safeFileName';
|
|
|
|
await _dio.download(
|
|
url,
|
|
filePath,
|
|
onReceiveProgress: (received, total) {
|
|
if (total != -1) {
|
|
int progress = (received / total * 100).toInt();
|
|
onProgress(progress);
|
|
}
|
|
},
|
|
);
|
|
|
|
onComplete(filePath);
|
|
return filePath;
|
|
} catch (e) {
|
|
onError(e.toString());
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
static String _getSafeFileName(String fileName) {
|
|
return fileName.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_');
|
|
}
|
|
} |