如何从Amazon S3将文件流式传输到Zip文件中

5

我正在使用 PHP Flysystem 包从我的 Amazon S3 存储桶中流式传输内容。特别地,我正在使用 $filesystem->readStream

我的问题

当我流式传输一个文件时,它最终变成了名为 myzip.zip.cpgz 的文件,大小是正确的。这是我的原型:

header('Pragma: no-cache');
header('Content-Description: File Download');
header('Content-disposition: attachment; filename="myZip.zip"');
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
$s3 = Storage::disk('s3'); // Laravel Syntax
echo $s3->readStream('directory/file.jpg');

我做错了什么?

附加问题

当我像这样流式传输文件时,它会:

  1. 完全下载到我的服务器RAM中,然后传输到客户端,还是
  2. 它会以块的形式保存在缓冲区中,然后传输到客户端?

基本上,如果我有数十GB的数据被流式传输,我的服务器是否会负担过重?

1个回答

2

您目前正在以zip格式转储directory/file.jpg的原始内容(jpg不是zip)。 您需要创建一个包含这些内容的zip文件。

与其这样做,

echo $s3->readStream('directory/file.jpg');

请使用Zip扩展来替换以下内容:
// use a temporary file to store the Zip file
$zipFile = tmpfile();
$zipPath = stream_get_meta_data($zipFile)['uri'];
$jpgFile = tmpfile();
$jpgPath = stream_get_meta_data($jpgFile)['uri'];

// Download the file to disk
stream_copy_to_stream($s3->readStream('directory/file.jpg'), $jpgFile);

// Create the zip file with the file and its contents
$zip = new ZipArchive();
$zip->open($zipPath);
$zip->addFile($jpgPath, 'file.jpg');
$zip->close();

// export the contents of the zip
readfile($zipPath);

使用 tmpfilestream_copy_to_stream,它会将文件分块下载到临时磁盘文件中,而不是下载到内存中。

在这种情况下,tmpfile()是什么?那应该是获取临时文件的路径吗? - mark.inman
1
@mark.inman PHP的tmpfile()函数“以读写(w+)模式创建一个带有唯一名称的临时文件,并返回一个文件句柄。” 要获取临时文件的路径,您可以执行stream_get_meta_data()函数并访问其返回值的uri,如下所示:$zipPath$jpgPath - bradynpoulsen

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