【问题标题】:How to Stream files into a Zip from Amazon S3如何将文件从 Amazon S3 流式传输到 Zip
【发布时间】:2016-11-21 07:18:40
【问题描述】:

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

我的问题

当我流式传输文件时,它以 myzip.zip 结尾,并且大小正确,但解压缩时,它变成 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 的数据正在流式传输,我的服务器是否会受到负担?

【问题讨论】:

    标签: php amazon-web-services amazon-s3 zip streaming


    【解决方案1】:

    您当前正在将directory/file.jpg 的原始内容转储为 zip(jpg 不是 zip)。您需要使用这些内容创建一个 zip 文件。

    而不是

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

    使用Zip extension 尝试以下操作:

    // 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 PHP 的tmpfile() 函数“在读写 (w+) 模式下创建一个具有唯一名称的临时文件并返回一个文件句柄。”要获取临时文件的路径,请执行 stream_get_meta_data() 函数并访问其返回值的 uri,如 $zipPath$jpgPath 所示。
    猜你喜欢
    • 2010-11-14
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    相关资源
    最近更新 更多