save_file_to_disk_handler.dart 1.15 KB
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;
      }
    }
  }
}