dshxbrzgi090608692 2016-11-21 07:18
浏览 598
已采纳

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

I'm using the PHP Flysystem package to stream content from my AWS S3 bucket. In particular, I'm using $filesystem->readStream.

My Question

When I stream a file, it ends up in myzip.zip and the size is correct, but when unzip it, it become myzip.zip.cpgz. Here is my prototype:

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');

What am I doing wrong?

Side Question

When I stream a file like this, does it:

  1. get fully downloaded into my server's RAM, then get transferred to the client, or
  2. does it get saved - in chunks - in the buffer, and then get transferred to the client?

Basically, is my server being burdened if I have have dozens of GB's of data being streamed?

  • 写回答

1条回答 默认 最新

  • dpw5865 2016-11-21 07:38
    关注

    You are currently dumping the raw contents of the directory/file.jpg as the zip (which a jpg is not a zip) . You need to create a zip file with those contents.

    Instead of

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

    Try the following in its place using the 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);
    

    Using tmpfile and stream_copy_to_stream, it will download it in chunks to a temporary file on disk and not into RAM

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)