代码之家  ›  专栏  ›  技术社区  ›  dikkini

如何创建ZIP存档并将其从C发送到Python并保存到文件系统?

  •  0
  • dikkini  · 技术社区  · 6 年前

    在C中,我用一些文件创建zip存档:

    using (MemoryStream ms = new MemoryStream())
    {
        using (ZipStorer zip = ZipStorer.Create(ms, "comment"))
        {
            zip.EncodeUTF8 = true;
            foreach (FileInfo logFile in logFiles)
            {
                zip.AddFile(ZipStorer.Compression.Deflate, logFile.FullName, logFile.Name, "");
            }
        }
        this.logger.log("memory stream to array");
        zipBytesArr = ms.ToArray();
    }
    

    它是有效的,因为当我在服务器上使用C#持久化zip归档文件时,我可以打开它。

    File.WriteAllBytes("C:\\test.zip", zipBytesArr);
    

    现在我把它作为字节数组发送 zipBytesArr 在POST请求中,我使用字段类型创建对象 byte[] JSON 然后发送。

    MyObject myObject = new MyObject()
    {
        // .. some fields
        ZipFileBytesArr = ZipFileBytesArr
    };
    var json = JsonConvert.SerializeObject(myObject);
    

    现在我想在python3(flask)中得到它,我有一些长字符串,我想创建zip存档。我的问题是:如何做到这一点?

    我试过这样的方法:

    bytes_as_str = "UEsDBBQAAAgIACyrWk4qVSmD0gYAAA4WAAAYAAAAMjAxOTAyMjZfb3BlbnZ...."
    bytes_as_bytes = bytes_as_str.encode(encoding="utf-8")
    file = zipfile.ZipFile(io.BytesIO(bytes_as_bytes))
    

    但它不起作用,我有个错误:

    zipfile.BadZipFile: File is not a zip file
    
    0 回复  |  直到 6 年前