yii框架里实现文件下载,及多文件压缩包下载
开发中,经常会用到下载文件,对文件下载需要以压缩包的形式下载下来,单文件下载有时候遇到图片或txt文件时,浏览器会直接输出,而不是以文件的形式下载,今天的例子适用于图片、txt文件、其他文件均已文件的形式下载:
代码实例,例如:
#单文件下载文件
#文件绝对地址
$filePath= 'https://www.test.com/file/测试.txt';
#获取文件名 测试.txt
$saveAsFileName = end(explode('/',$filePath));
#这里获取文件名,不可用pathinfo()函数,basename虽然一般在本地可以正常获取,但是提交阿里服务器时,有时会出现获取不到,获取不完整的情况,我遇到的是只获取到了后缀,文件名缺失
public function downloadFile($filePath, $saveAsFileName)
{
$filename = $filePath;
$saveAsFileName = iconv('utf8', 'gbk', $saveAsFileName);
$file = fopen($filename, "rb");
Header("Content-type: application/octet-stream ");
Header("Accept-Ranges: bytes ");
Header("Content-Disposition: attachment; filename= {$saveAsFileName}");
$contents = "";
while (!feof($file)) {
$contents .= fread($file, 8192);
}
echo $contents;
fclose($file);
}
#多文件以压缩包的形式下载
public function downLoadFiles(){
$filePath = [
'https://www.test.com/file/小草.jpg',
'https://www.test.com/file/测试.txt',
'https://www.test.com/file/通关考试.doc',
'https://www.test.com/file/答案.docx',
];
$tmpFile = tempnam('/tmp', '');
$zip = new ZipArchive;
$zip->open($tmpFile, ZipArchive::CREATE);
foreach ($files as $file) {
// download file
$fileContent = file_get_contents($file);
$file = iconv('utf-8', 'GBK', basename($file));
$zip->addFromString($file, $fileContent);
}
$zip->close();
header('Content-Type: application/zip;charset=utf8');
header('Content-disposition: attachment; filename=附件' . date('Y-m-d') . '.zip');
header('Content-Length: ' . filesize($tmpFile));
readfile($tmpFile);
unlink($tmpFile);
}