首頁  >  文章  >  後端開發  >  ThinkPHP實作批次打包下載文件

ThinkPHP實作批次打包下載文件

小云云
小云云原創
2018-05-15 14:38:454171瀏覽

有數個文件,包含圖片,文檔。需根據條件自動打包成壓縮包,提供下載。本文主要為大家介紹利用PHP或ThinkPHP如何實現大量打包下載檔案的方法範例,需要的朋友可以參考借鑒,希望能幫助大家。

解決(ZipArchive 類別):

PHP提供了ZipArchive 類別可為我們實現這一功能,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);
 
?>

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

區別在引用的時候路徑要對,結束。

相關推薦:

React 和Webpack建置打包優化實例詳解

parcel.js打包出錯到選擇nvm的全部過程解析

vue打包後顯示空白如何處理


#

以上是ThinkPHP實作批次打包下載文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn