choose_file_handler.dart
2.72 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
import 'dart:io';
import 'package:appframe/services/dispatcher.dart';
import 'package:appframe/utils/file_type_util.dart';
import 'package:appframe/utils/thumbnail_util.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_size_getter/file_input.dart';
import 'package:image_size_getter/image_size_getter.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
class ChooseFileHandler extends MessageHandler {
@override
Future<dynamic> handleMessage(dynamic params) async {
if (params is! Map<String, dynamic>) {
throw Exception('参数错误');
}
var count = params['count'] as int;
var fileTypes = params['fileTypes'] as List<dynamic>;
FilePickerResult? filePickerResult = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: fileTypes.map((e) => e.toString()).toList(),
allowMultiple: count > 1,
);
// 用户取消选择,返回空数组
if (filePickerResult == null) {
return [];
}
// 限制最多count个文件
if (filePickerResult.files.length > count) {
filePickerResult.files.removeRange(count, filePickerResult.files.length);
}
final List<Map<String, dynamic>> result = [];
for (var file in filePickerResult.files) {
result.add(await _handleFile(file));
}
return result;
}
Future<Map<String, dynamic>> _handleFile(PlatformFile file) async {
// 获取临时目录
final tempDir = await getTemporaryDirectory();
// 临时文件路径
final uniqueFileName = '${DateTime.now().millisecondsSinceEpoch}_${file.name}';
final tempFilePath = path.join(tempDir.path, uniqueFileName);
// 复制
final originalFile = File(file.path!);
final copiedFile = await originalFile.copy(tempFilePath);
bool isImage = await FileTypeUtil.isImage(copiedFile);
bool isVideo = false;
if (!isImage) {
isVideo = await FileTypeUtil.isVideo(copiedFile);
}
// 通过image_size_getter获取图片尺寸
SizeResult? sizeResult;
String? thumbTempFilePath;
if (isImage) {
sizeResult = ImageSizeGetter.getSizeResult(FileInput(copiedFile));
thumbTempFilePath = await ThumbnailUtil.genTempThumbnail(copiedFile, tempDir);
}
if (isVideo) {
thumbTempFilePath = await ThumbnailUtil.genVideoThumbnail(copiedFile.path, tempDir);
}
// 返回临时文件信息
return {
'tempFilePath': tempFilePath,
'size': file.size,
'width': sizeResult != null ? sizeResult.size.width : '',
'height': sizeResult != null ? sizeResult.size.height : '',
'thumbTempFilePath': thumbTempFilePath ?? '',
'fileType': copiedFile.path.split('/').last.split('.').last,
};
}
}