nemo64/zip-stream

快速流式传输多个文件,无需首先创建归档。

v1.0.0 2019-01-28 15:43 UTC

This package is auto-updated.

Last update: 2024-09-29 03:20:48 UTC


README

Build Status Latest Stable Version Total Downloads Monthly Downloads License

ZIP 流

此库允许您创建一个包含多个文件的 zip 格式 PSR-7 流。这个过程不需要实际创建 zip 文件,因此对资源的占用非常小。事实上,与仅仅通过 php 发送文件相比,差异应该很小。

以下是它的特殊特性:

  • 不会创建文件,因此不需要清理
  • 在发送文件之前即可知道文件长度,这使得可能的 Content-Length 头(这会让用户知道下载需要多长时间)
  • 如果您的 psr7-emitter/framework 支持,则可以恢复下载。
  • 您不必将流输出到浏览器,例如,您可以在 POST 请求中使用 guzzle 进行流式传输。
  • 没有平台依赖。您不需要在您的机器上安装 ext-zip 或 zip 命令。

但也有一些限制:

  • 创建的 zip 文件完全没有压缩。这是快速计算大小所必需的。如果您需要这个功能,请使用 maennchen/zipstream-php
  • 尚未实现 Zip64,因此您被限制在 4GB 文件内。在 32 位 php 中可能会有其他限制,但我尚未研究。

示例

您需要一种方式将 PSR-7 响应对象发送到客户端。一些框架开始支持这一点,但在此期间,我建议您使用像 arrowspark/http-emitter 这样的外部库来完成这项工作。

use function GuzzleHttp\Psr7\stream_for;
use function GuzzleHttp\Psr7\try_fopen;
use Narrowspark\HttpEmitter\SapiStreamEmitter;
use Nemo64\ZipStream\ZipResponse;
use Nemo64\ZipStream\ZipStream;

$zip = new ZipStream();
$zip->add('file1.jpg', stream_for(try_fopen('file1.jpg', 'r')));

// be sure that before you send this response that there is no output buffering engaged.
while (@ob_end_clean()) {}

$response = ZipResponse::create($zip, 'my_archive.zip');
$emitter = new SapiStreamEmitter();
$emitter->emit($response);