ThinkPHP implements batch packaging and downloading files

小云云
Release: 2023-03-19 19:08:01
Original
4236 people have browsed it

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(&#39;image.jpeg&#39;,&#39;text.txt&#39;,&#39;music.wav&#39;);
$zipname = &#39;enter_any_name_for_the_zipped_file.zip&#39;;
$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);
 
?>
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template