Home > Article > Backend Development > ThinkPHP implements batch packaging and downloading files
There are several files, including pictures and documents. It needs to be automatically packaged into a compressed package according to conditions and provided for download. This article mainly introduces you to examples of how to use PHP or ThinkPHP to package and download files in batches. Friends who need it can refer to it. I hope it can help everyone.
Solution (ZipArchive class):
PHP provides the ZipArchive class to realize this function for us, 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 version
$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);
Difference The path must be correct when quoting, end.
Related recommendations:
Detailed explanation of React and Webpack construction and packaging optimization examples
parcel.js packaging error to choose nvm Analysis of the entire process
How to deal with the blank display after vue is packaged
The above is the detailed content of ThinkPHP implements batch packaging and downloading files. For more information, please follow other related articles on the PHP Chinese website!