批量打包下载阿里OSS文件

有需求的地方就有方法,批量下载oss文件,上一章说的是从前端的角度实现批量一个个间断性下载,但是存在一定问题(1.用户体验不好,2.多次下载或弹窗需要修改浏览器配置,且有时候存在请求被取消的风险,操作人员如果不核实文件个数有时候很难发现这个问题,这对统计工作有一定风险),本文章是从后端接口,批量请求阿里oss获取下载文件内容,将获取到的数据打包一次性下载:

class TestOss extends BaseController
{
    //初测
	public function test()
	{
		$objectName = 'abc/2021/10/30/G20211030060001231.xlsx';
		$object = self::$oss->getObject($this->config['oss']['bucket'], $objectName);
  		$file = 'abc' . substr($objectName, strrpos($objectName, '.'));

		$fp = fopen ($file, 'w');
		fwrite($fp, $object);
		fclose($fp);
	}
    
    //打包下载
	public function testZip()
	{
		error_reporting(E_ALL);
		ini_set('display_errors', true);

		$zip = new ZipArchive;
		$tmpFileName = './tmpzip' . mt_rand(100, 999);
		$res = $zip->open($tmpFileName, ZipArchive::CREATE);
		var_dump(is_file($tmpFileName));

		$objectName = 'abc/1077/2021/10/30/G20211030060001231.xlsx';
		$object = self::$oss->getObject($this->config['oss']['bucket'], $objectName);
  		$file = 'abc' . substr($objectName, strrpos($objectName, '.'));

		if ($res === TRUE) {
		    $zip->addFromString($file, $object);
		    $zip->close();
		    $tarFile = 'abc.zip';
			var_dump(is_file($tmpFileName));
			$fileSize = filesize($tmpFileName);
			$fp = fopen($tmpFileName, "r");
			header("Content-type: application/octet-stream");
			header("Accept-Ranges: bytes");
			header("Accept-Length: " . $fileSize);
			header("Content-Disposition: attachment; filename=" . $tarFile); 
			$buffer = 1024;
			$fileCount = 0;
			while (!feof($fp) && $fileCount < $fileSize) {
				$fileCon = fread($fp, $buffer);
				$fileCount += $buffer;
				echo $fileCon;
			}
			fclose($fp);
			unlink($tmpFileName);
		} else {
		    echo 'failed';
		}
	}

}

(new TestOss())->testZip();

你可能感兴趣的:(php,php,oss)