dqmfo84644 2015-01-29 19:03
浏览 40
已采纳

将多个图像下载到zip中

I am trying to add functionality to my website where users can download multiple image files via a single .zip folder. Currently I have this code executing but when i open the downloaded zip file it extracts another zip file my-archive (3) 2.zip.cpgz and every time I try to open it, it extracts yet another zip file.

Here is my basic code using php native zip feature.

$image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";

$files = array($image1, $image2);
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
    $zip->addFile($file);
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

EDIT

I am trying hard to get the provided answer to work. I just tried the most recent edit and got this error

[]

  • 写回答

2条回答 默认 最新

  • dqenv99518 2015-01-29 19:11
    关注

    You should download external files and then archive them.

    $image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
    $image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
    
    $files = array($image1, $image2);
    
    $tmpFile = tempnam('/tmp', '');
    
    $zip = new ZipArchive;
    $zip->open($tmpFile, ZipArchive::CREATE);
    foreach ($files as $file) {
        // download file
        $fileContent = file_get_contents($file);
    
        $zip->addFromString(basename($file), $fileContent);
    }
    $zip->close();
    
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename=file.zip');
    header('Content-Length: ' . filesize($tmpFile));
    readfile($tmpFile);
    
    unlink($tmpFile);
    

    In example above I used file_get_contents function, so please enable allow_url_fopen or use curl to download the files.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!