小编给大家分享一下PHP/ThinkPHP如何实现批量打包下载文件,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
需求描述:
有数个文件,包含图片,文档。需要根据条件自动打包成压缩包,提供下载。
解决(ZipArchive 类):
PHP提供了ZipArchive 类可为我们实现这一功能,demo:
<?php
$files = array('image.jpeg','text.txt','music.wav');
$zipname = 'enter_any_name_for_the_zipped_file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
///Then download the zipped file.
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
?>
ThinkPHP版
$zip = new \ZipArchive;
//压缩文件名
$filename = 'download.zip';
//新建zip压缩包
$zip->open($filename,\ZipArchive::OVERWRITE);
//把图片一张一张加进去压缩
foreach ($images as $key => $value) {
$zip->addFile($value);
}
//打包zip
$zip->close();
//可以直接重定向下载
header('Location:'.$filename);
//或者输出下载
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($filename)); //文件名
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename)); //告诉浏览器,文件大小
readfile($filename);
区别在引用的时候路径要对,结束。
看完了这篇文章,相信你对“PHP/ThinkPHP如何实现批量打包下载文件”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。