【问题标题】:Download multiple images into zip将多个图像下载到 zip
【发布时间】:2015-01-29 19:03:18
【问题描述】:

我正在尝试向我的网站添加功能,用户可以通过单个 .zip 文件夹下载多个图像文件。目前我正在执行此代码,但是当我打开下载的 zip 文件时,它会提取另一个 zip 文件 my-archive (3) 2.zip.cpgz 并且每次我尝试打开它时,它都会提取另一个 zip 文件。

这是我使用 php 原生 zip 功能的基本代码。

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

编辑

我正在努力使提供的答案起作用。我刚刚尝试了最近的编辑并得到了这个错误

]

【问题讨论】:

    标签: php


    【解决方案1】:

    您应该下载外部文件,然后将它们存档。

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

    在上面的例子中我使用了file_get_contents函数,所以请启用allow_url_fopen或者使用curl来下载文件。

    【讨论】:

    • 感谢您的回答。我有同样的问题。根据您的示例,我正在使用file_get_contents,但仍然无法正常工作。
    • 我检查过,为我工作。可能是权限问题,您可以尝试使用tempnam函数创建临时文件。
    • 我刚试过echo tempnam("/","TMP0");,它回显了/tmp/TMP0hwzkRX,所以我可以假设权限没问题?
    • 我刚刚尝试了您的最新编辑并弹出错误消息。我已将弹出窗口的图像上传到我的编辑问题。
    • 当我尝试将它与 data:url 图像一起使用时它失败了,这就是我只使用它的目的。你知道用数据 uri 图像实现这一点的最佳方法吗?
    【解决方案2】:

    大家好,上面的代码运行良好。图像下载仅在实时服务器上有效(仅当我们使用 https 或 http 时)。但它不适用于本地(如果我们使用 https 或 http).. 如果您使用本地,请遵循此 -> 仅更改以下行。 用于img以下的本地使用 $image1 = "C:/Users/User/Pictures/Saved Pictures/chandamama.jpg"; $image2 = "C:/Users/User/Pictures/Saved Pictures/beautifull.jpg"; 不要在本地使用低于 img 的。 $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";

    【讨论】:

      猜你喜欢
      • 2015-10-25
      • 2020-12-14
      • 2020-01-28
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 2019-03-01
      • 2017-04-08
      • 2020-02-29
      相关资源
      最近更新 更多