save_file_to_disk_handler.dart
1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import 'dart:io';
import 'package:appframe/services/dispatcher.dart';
import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path/path.dart' as path;
class SaveFileToDisKHandler extends MessageHandler {
@override
Future<dynamic> handleMessage(params) async {
if (params is! Map<String, dynamic>) {
throw Exception('参数错误');
}
var filePath = params['filePath'] as String;
if (filePath.isEmpty) {
throw Exception('参数错误');
}
// 让用户选择保存目录
String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
// 获取filePath中的文件名,以及后缀名
var fileName = path.basenameWithoutExtension(filePath);
var ext = path.extension(filePath);
// 要保存的路径
var targetPath = path.join(selectedDirectory!, '$fileName.$ext');
// 如果文件存在,则在文件名后添加数字
int i = 1;
while (File(targetPath).existsSync()) {
targetPath = path.join(selectedDirectory, '$fileName($i).$ext');
i++;
}
if (filePath.startsWith('http')) {
final resp = await Dio().download(filePath, targetPath);
if (resp.statusCode != 200) {
throw Exception('文件下载失败');
}
return true;
} else {
// 将filePath路径的文件保存到targetPath
final f = await File(filePath).copy(targetPath);
if (f.existsSync()) {
return true;
} else {
return false;
}
}
}
}