Flutter中无法解压缩zip文件。

5
从服务器下载zip文件并尝试提取zip文件,但该zip文件具有多个目录。我可以下载zip文件,但无法提取它。以下代码适用于当zip文件具有多个图像文件时的情况,但在我的情况下,该zip文件具有多个目录和多个文件。
String _localZipFileName = 'archive.zip';

  Future<File> _downloadFile(String url, String fileName) async {
    //url==http://115.166.142.178:3000/staff/syncdata
    var req = await http.Client().get(Uri.parse(url));
    Log.e("DOWNLOAD DIRECTORY",_dir);
    var file = File('$_dir/$fileName');
    return file.writeAsBytes(req.bodyBytes);
  }

  Future<void> _downloadZip(String _zipPath) async {
setState(() {
  _downloading = true;
});

Log.e("Zippath",_zipPath);
_images.clear();
_tempImages.clear();
var zippedFile = await _downloadFile(_zipPath, _localZipFileName);
Log.e("Zippath",zippedFile.path);
await unarchiveAndSave(zippedFile);
setState(() {
  _images.addAll(_tempImages);
  _downloading = false;
});
  }



 unarchiveAndSave(var zippedFile) async {
    var bytes = zippedFile.readAsBytesSync();
    var archive = ZipDecoder().decodeBytes(bytes);

for (var file in archive) {
  var fileName = '$_dir/${file.name}';
  if (file.isCompressed) {
    var outFile = File(fileName);
    Log.e('File:: ' , outFile.path);
   // _tempImages.add('${outFile.path}/productImages');
    outFile = await outFile.create(recursive: true);
    await outFile.writeAsBytes(file.content);
  }
}
  }
3个回答

2
存档包有一个名为“extractFileToDisk”的方法,可以实现您想要的功能。具体信息请参见此链接

1

我从未尝试在Dart中这样做,但我在其他语言中遇到过类似的问题。通常,如果您忘记验证正在处理的文件类型,则会出现问题。文件对象应该有布尔变量file.isFilefile.isDirectory

您可以尝试按照此示例操作。

import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:path/path.dart';
import 'package:archive/archive.dart';
import 'package:archive/archive_io.dart';

var path = p.Context(style: Style.posix);
final String __filename = Platform.script.path.replaceFirst('/', '');
final String __dirname = Directory(__filename).parent.path;

  // read Zip file from disk
  List<int> bytes = File(path.join(__dirname, 'test-a-master.zip')).readAsBytesSync();

     // decode Zip file
  Archive archive = ZipDecoder().decodeBytes(bytes);

     // Extract the contents of Zip compressed archive to disk
  for (ArchiveFile file in archive) {
    String filename = file.name;
    String decodePath = path.join(__dirname, filename);
    if (file.isFile) {
      List<int> data = file.content;
      File(decodePath)
        ..createSync(recursive: true)
        ..writeAsBytesSync(data);
    } else {
      Directory(decodePath)..create(recursive: true);
    }
  }

希望它能对你有所帮助。

ArchiveFile 给出父级压缩文件的文件名。 - Farhana Naaz Ansari

0

2
我找到了问题。问题是压缩包中包含了另一个压缩包。 - Farhana Naaz Ansari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接