You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在内存中压缩Zip文件并获取其原始内容(Delphi)

内存中压缩文件为Zip并获取原始字节内容

要在内存中完成Zip压缩并获取可存入数据库的字节数组,不能直接通过TZipFile.Data属性获取结果——该属性并非存储完整的压缩后Zip数据。正确的做法是借助TMemoryStream作为Zip的输出载体,具体实现如下:

function GetZip(UncompressedFile: TStream): TBytes;
var
  AZipFile: TZipFile;
  MemStream: TMemoryStream;
begin
  MemStream := TMemoryStream.Create;
  AZipFile := TZipFile.Create;
  try
    // 初始化Zip写入到内存流
    AZipFile.Open(MemStream, zmWrite);
    try
      // 确保从原始流的起始位置读取
      UncompressedFile.Position := 0;
      // 添加流到Zip,第二个参数是Zip包内的文件名(必须指定)
      AZipFile.Add(UncompressedFile, 'CompressedFile');
    finally
      // 完成Zip写入并关闭
      AZipFile.Close;
    end;
    // 将内存流中的Zip数据转换为TBytes
    SetLength(Result, MemStream.Size);
    if MemStream.Size > 0 then
    begin
      MemStream.Position := 0;
      MemStream.ReadBuffer(Result[0], MemStream.Size);
    end;
  finally
    AZipFile.Free;
    MemStream.Free;
  end;
end;

关键说明

  • 使用TMemoryStream作为Zip的输出目标,完全规避文件系统操作。
  • 调用AZipFile.Open时指定zmWrite模式,开启内存写入逻辑。
  • AZipFile.Add方法必须传入第二个参数(Zip包内的文件名),否则会抛出异常。
  • 转换为TBytes前,需将内存流的Position重置为0,确保读取完整的压缩数据。

内容的提问来源于stack exchange,提问作者Marc Guillot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:56:04