zip static method

Future<String> zip(
  1. String sourcePath,
  2. String targetPath
)

压缩文件/文件夹(不加密) sourcePath 源文件/文件夹路径 targetPath 目标zip文件路径

Implementation

static Future<String> zip(String sourcePath, String targetPath) async {
  try {
    final sourceDir = Directory(sourcePath);
    final archive = Archive();

    // 如果是目录,递归添加文件
    if (await sourceDir.exists()) {
      await for (final file in sourceDir.list(recursive: true)) {
        if (file is File) {
          final relativePath = file.path.substring(sourcePath.length);
          final data = await file.readAsBytes();
          archive.addFile(ArchiveFile(
            relativePath,
            data.length,
            data,
          ));
        }
      }
    }
    // 如果是单个文件
    else if (await File(sourcePath).exists()) {
      final file = File(sourcePath);
      final data = await file.readAsBytes();
      archive.addFile(ArchiveFile(
        file.path.split('/').last,
        data.length,
        data,
      ));
    } else {
      throw Exception('源文件/文件夹不存在');
    }

    // 压缩并保存
    final zipData = ZipEncoder().encode(archive);
    final zipFile = File(targetPath);
    await zipFile.writeAsBytes(zipData);
    await Future.delayed(const Duration(milliseconds: 100));
    return targetPath;
  } catch (e) {
    throw Exception('压缩错误: $e');
  }
}