open_document_handler.dart
2.71 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
88
89
import 'dart:io';
import 'package:appframe/services/dispatcher.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
class OpenDocumentHandler extends MessageHandler {
@override
Future<dynamic> handleMessage(params) async {
if (params is! Map<String, dynamic>) {
throw Exception('参数错误');
}
final url = params['url'] as String?;
if (url == null || url.isEmpty) {
throw Exception('参数错误');
}
if (url.startsWith("http://")) {
await saveNetworkImageToExternalStorage(url);
} else {
await saveLocalFileToExternalStorage(url);
}
}
Future<bool> saveLocalFileToExternalStorage(String sourcePath) async {
try {
// 获取外部存储目录
final directory = await getExternalStorageDirectory();
// 获取文件名
final fileName = sourcePath.split('/').last;
var destinationPath = '${directory?.path}/$fileName';
// 检查文件是否存在,如果存在则生成新文件名
var counter = 1;
while (await File(destinationPath).exists()) {
final extension = fileName.split('.').last;
final nameWithoutExtension = fileName.substring(0, fileName.length - extension.length - 1);
destinationPath = '${directory?.path}/${nameWithoutExtension}_$counter.$extension}';
counter++;
}
// 复制文件
final sourceFile = File(sourcePath);
await sourceFile.copy(destinationPath);
return true;
} catch (e) {
print('保存文件失败: $e');
return false;
}
}
Future<bool> saveNetworkImageToExternalStorage(String imageUrl) async {
try {
// 获取外部存储目录
final directory = await getExternalStorageDirectory();
// 从URL获取文件名
final fileName = imageUrl.split('/').last;
var filePath = '${directory?.path}/$fileName';
// 检查文件是否存在,如果存在则生成新文件名
var counter = 1;
while (await File(filePath).exists()) {
final extension = fileName.split('.').last;
final nameWithoutExtension = fileName.substring(0, fileName.length - extension.length - 1);
filePath = '${directory?.path}/${nameWithoutExtension}_$counter.$extension}';
counter++;
}
// 下载网络图片
final response = await http.get(Uri.parse(imageUrl));
if (response.statusCode == 200) {
// 保存到外部存储
final file = File(filePath);
await file.writeAsBytes(response.bodyBytes);
return true;
} else {
print('下载失败: ${response.statusCode}');
return false;
}
} catch (e) {
print('保存失败: $e');
return false;
}
}
}