choose_image_handler.dart
2.68 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import 'dart:io';
import 'package:appframe/services/dispatcher.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
class ChooseImageHandler implements MessageHandler {
@override
Future<dynamic> handleMessage(Map<String, dynamic> params) async {
try {
// 初始化图片选择器
final ImagePicker picker = ImagePicker();
// 选择图片
final XFile? pickedFile = await picker.pickImage(
source: ImageSource.gallery, // 可以改为 ImageSource.camera 用于拍照
);
if (pickedFile != null) {
// 获取临时目录
final Directory tempDir = await getTemporaryDirectory();
// 生成唯一文件名
final String fileName = path.basename(pickedFile.path);
final String uniqueFileName = '${DateTime.now().millisecondsSinceEpoch}_$fileName';
// 创建目标文件路径
final String tempFilePath = path.join(tempDir.path, uniqueFileName);
// 复制文件到临时目录
final File copiedFile = await File(pickedFile.path).copy(tempFilePath);
// 返回临时文件路径
// 前面加上特殊路径,用于后续处理
return "/temp${copiedFile.path}";
}
return null; // 用户取消选择
} catch (e) {
print(e);
return null;
}
}
Future<List<Map<String, dynamic>>?> _selectOne(String sourceType) async {
final ImagePicker picker = ImagePicker();
final XFile? pickedFile = await picker.pickImage(
source: sourceType == 'album' ? ImageSource.gallery : ImageSource.camera,
);
if (pickedFile != null) {
// 获取临时目录
final Directory tempDir = await getTemporaryDirectory();
// 生成唯一文件名
final String fileName = path.basename(pickedFile.path);
final String uniqueFileName = '${DateTime.now().millisecondsSinceEpoch}_$fileName';
// 创建目标文件路径
final String tempFilePath = path.join(tempDir.path, uniqueFileName);
// 复制文件到临时目录
final File copiedFile = await File(pickedFile.path).copy(tempFilePath);
// 返回一个元素的数组
return [
{
"tempFilePath": "/temp${copiedFile.path}",
"size": copiedFile.lengthSync(),
"fileType": copiedFile.path.split('/').last.split('.').last,
},
];
} else {
return null;
}
}
/*Future<List<Map<String, dynamic>>?> _selectMulti(int count, String sourceType) async {
final ImagePicker picker = ImagePicker();
List<XFile> fileList = await picker.pickMultiImage();
if (fileList.isNotEmpty) {
}
}*/
}