save_file_to_disk_handler.dart 1.49 KB
import 'dart:io';

import 'package:appframe/services/dispatcher.dart';
import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path/path.dart' as path;

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? selectedDirectory = await FilePicker.platform.getDirectoryPath();
    // 获取filePath中的文件名,以及后缀名
    var fileName = path.basenameWithoutExtension(filePath);
    var ext = path.extension(filePath);
    // 要保存的路径
    var targetPath = path.join(selectedDirectory!, '$fileName.$ext');
    // 如果文件存在,则在文件名后添加数字
    int i = 1;
    while (File(targetPath).existsSync()) {
      targetPath = path.join(selectedDirectory, '$fileName($i).$ext');
      i++;
    }

    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;
      }
    }
  }
}