PHP文件下载有单文件和多文件之分,如果是单文件写个方法可以实现,但是如果想循环下载多个文件我试验是没有成功。先说单文件的下载,方法如下:
function downfile($fileurl) {
$filenameexplode=explode('/',$fileurl);
$fileRealName=$filenameexplode[count($filenameexplode)-];
$filename=$fileurl;
$file = fopen($filename, "rb");
Header( "Content-type: application/octet-stream ");
Header( "Accept-Ranges: bytes ");
Header( "Content-Disposition: attachment; filename= ".$fileRealName);
$contents = "";
while (!feof($file)) {
$contents .= fread($file, );
}
echo $contents;
fclose($file);
}
如果是多个文件,可以采用压缩下载的方式进行下载,以下代码是读取excel中文件地址并打包下载的源码:
set_time_limit();
ini_set("max_execution_time", );
ini_set("memory_limit", "1G");
require_once 'Excel/PHPExcel/IOFactory.php';
$filePath ='pdforimg.xlsx';
$fileType = PHPExcel_IOFactory::identify($filePath);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($filePath); //$sheet = $objPHPExcel->getSheet(); // 读取第一個工作表 $arr = $objPHPExcel->getActiveSheet()->toArray();
foreach($arr as $k=>$v){
if($k>=){
foreach($arr[] as $kk=>$vv){
$isnull=str_replace(' ','',$v[]);
if(!($isnull) || $isnull==" "){
break;
}
$data[$k-][$arr[][$kk]]=$v[$kk];
}
}
} $filename = 'tmp.zip'; $zip = new ZipArchive();
$zip->open($filename, ZipArchive::OVERWRITE); foreach ($data as $key=>$vo) {
if($key>= && $key<){
$filenameexplode=explode('/',$vo['url']);
$fileRealName=$filenameexplode[count($filenameexplode)-];
$fileData = file_get_contents($vo['url']);
if ($fileData) {
$zip->addFromString($fileRealName, $fileData);
}
} } $zip->close(); $file = fopen($filename, "r");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: " . filesize($filename));
Header("Content-Disposition: attachment; filename=pdf.zip");
//一次只传输1024个字节的数据给客户端
$buffer = ; //
while (!feof($file)) {
//将文件读入内存
$file_data = fread($file, $buffer);
//每次向客户端回送1024个字节的数据
echo $file_data;
}
fclose($file);
unlink($filename);
excel内容如下图所示:
打包过程参考:https://www.cnblogs.com/shaoyikai/p/3755079.html