后端代碼
// 批量下載并壓縮
public function downloadAll(){$ids = input('ids');$row = $this->model->where('id', 'in', $ids)->field('id,title,video_url')->select();if (!$row) {$this->error('記錄不存在');}$arr = [];$tempFiles = []; // 用來存儲臨時下載的視頻文件路徑// 打包視頻文件的 ZIP 文件名$zipname = '視頻文件[' . str_replace(',', '_', $ids) . ']' . date('YmdHis') . '.zip';// 初始化 ZIP 壓縮包$zip = new \ZipArchive();if ($zip->open($zipname, \ZIPARCHIVE::CREATE) !== TRUE) {$this->error('無法創建壓縮包');}foreach ($row as $item) {// 假設視頻鏈接存儲在數據庫中的 'video_url' 字段$videoUrl = $item['video_url']; // 遠程視頻的 URL$fileName = basename($videoUrl); // 獲取文件名// 直接通過 HTTP 流式讀取遠程文件并將其寫入到 ZIP 中if ($this->addRemoteFileToZip($zip, $videoUrl, $fileName)) {$arr[] = $fileName; // 添加到數組}}if (empty($arr)) {$this->error('沒有可下載的視頻文件');}// 關閉 ZIP 文件$zip->close();// 發送到瀏覽器\fast\Http::sendToBrowser($zipname);
}/*** 將遠程文件流式讀取并添加到 ZIP 壓縮包* @param ZipArchive $zip ZipArchive 對象* @param string $url 遠程文件 URL* @param string $fileName 壓縮包中的文件名* @return bool 是否成功*/
private function addRemoteFileToZip($zip, $url, $fileName) {// 打開遠程文件的 URL 進行流式讀取$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 允許 URL 重定向curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 設置超時時間$fileContent = curl_exec($ch);if (curl_errno($ch)) {curl_close($ch);return false; // 下載失敗}// 獲取文件內容并關閉 cURLcurl_close($ch);// 將內容添加到 ZIP 文件if ($fileContent !== false) {$zip->addFromString($fileName, $fileContent); // 使用文件名和內容添加到 ZIP 中return true;}return false;
}
前端js代碼
//批量下載$(document).on("click", ".btn-download", function () {var selectedrow = table.bootstrapTable('getSelections');if(selectedrow.length<1){Toastr.error('未選擇任何記錄,不能下載!');return;}var ids = [];for(var i=0;i<selectedrow.length;i++){ids[i] = selectedrow[i].id;// 遍歷選擇記錄}location.href='/admin/downloadAll?ids='+ids.join(',')});