save_file_to_disk_handler.dart
1.15 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
import 'dart:io';
import 'package:appframe/services/dispatcher.dart';
import 'package:dio/dio.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
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 ext = path.extension(filePath);
final Directory tempDir = await getApplicationDocumentsDirectory();
final targetPath = path.join(tempDir.path, '${DateTime.now().millisecondsSinceEpoch}$ext');
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;
}
}
}
}