Как сохранить zip-архив в общедоступную папку в laravel? - PullRequest
0 голосов
/ 09 января 2019

Я хочу скачать папку в формате ZIP с моим кодом ниже.

На самом деле это прекрасно работает только для загрузки папки в zip.

Но я хочу, чтобы zip-файл также сохранялся в общую папку в public / folder. я использую laravel и ziparchive

Пожалуйста, помогите мне

 public function downloadzip($id_pra) {
     $dcmt = DB::table('document')->select(DB::raw(" max(id) as id"))->where('id_praapplication',$id_pra)->groupBy('type')->pluck('id');

     $files = Document::whereIn('id', $dcmt)->get(); 

     $url = url('')."/storage/uploads/file/".$id_pra."/"; 

     # create new zip opbject
     $zip = new \ZipArchive();

     # create a temp file & open it
     $tmp_file = tempnam('.','');
     $zip->open($tmp_file, \ZipArchive::CREATE);
     # loop through each file

     foreach($files as $file){
         $url2 = $url.$file->upload;
         $url2 = str_replace(' ', '%20', $url2);

         if (!function_exists('curl_init')){ 
             die('CURL is not installed!');
         }

         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url2);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         $output = curl_exec($ch);
         curl_close($ch);
         $download_file = $output;

         $type = substr($url2, -5, 5); 
         #add it to the zip
         $zip->addFromString(basename($url.$file->upload.'.'.$type),$download_file);
     }

     # close zip
     $zip->close();

     # send the file to the browser as a download
     ob_start();
     $strFile = file_get_contents($tmp_file);         
     header('Content-disposition: attachment; filename=DOC-'.$id_pra.'-'.$url.'.zip');
     header('Content-type: application/zip');
     echo $tmp_file;
     while (ob_get_level()) {
         ob_end_clean();
     }

     readfile($tmp_file);
     exit;   
}

1 Ответ

0 голосов
/ 09 января 2019

Вместо создания временного файла вы можете просто создать ZIP-файл напрямую, а затем использовать API файловой системы для его загрузки.

public function downloadzip($id_pra) {
     $dcmt = DB::table('document')->select(DB::raw(" max(id) as id"))->where('id_praapplication',$id_pra)->groupBy('type')->pluck('id');

     $files = Document::whereIn('id', $dcmt)->get(); 

     $url = url('')."/storage/uploads/file/".$id_pra."/"; 

     // create new zip object
     $zip = new \ZipArchive();

     // store the public path
     $publicDir = public_path();

     // Define the file name. Give it a unique name to avoid overriding.
     $zipFileName = 'Documents.zip';

     // Create the ZIP file directly inside the desired folder. No need for a temporary file.
     if ($zip->open($publicDir . '/folder/' . $zipFileName, \ZipArchive::CREATE) === true) {
         // Loop through each file
         foreach($files as $file){
             $url2 = $url.$file->upload;
             $url2 = str_replace(' ', '%20', $url2);

             if (!function_exists('curl_init')){ 
                 die('CURL is not installed!');
             }

             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, $url2);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             $output = curl_exec($ch);
             curl_close($ch);
             $download_file = $output;

             $type = substr($url2, -5, 5); 
             #add it to the zip
             $zip->addFromString(basename($url.$file->upload.'.'.$type),$download_file);
         }

         // close zip
         $zip->close();
     }

     // Download the file using the Filesystem API
     $filePath = $publicDir . '/folder/' . $zipFileName;

     if (file_exists($filePath)) {
         return Storage::download($filePath);
     }
}

Примечание:

Я бы извлек часть CURL в метод fetchFile($url);, который возвращает загруженный файл, но это выходит за рамки этого вопроса.

...