2017-07-31 209 views
0

我想下載帶有許多圖像的zip文件。這個代碼工作時,當我在瀏覽器中調用路徑,但沒有下載時,我從Jquery ajax.Need調用需要更改或添加任何東西標題?請幫忙。Zip文件不是在Yii2下載

控制器:

public function actionZipdownload(){ 

    $files = Yii::$app->request->post('imgsrc'); 
    //it displays the URLs. 

    $zip = new \ZipArchive(); 

    $tmp_file = tempnam('.', ''); 

    $zip->open($tmp_file, ZipArchive::CREATE); 

    foreach ($files as $file) { 
     $download_file = file_get_contents($file); 
     $zip->addFromString(basename($file), $download_file); 
    } 

    $zip->close(); 

    header('Content-disposition: attachment; filename="my file.zip"'); 
    header('Content-type: application/zip'); 
    readfile($tmp_file); 
    unlink($tmp_file); 
} 

jQuery的

$.ajax({ 
    url:url+'site/zipdownload', 
    data:{'imgsrc':imgsrc}, 
    type:'POST', 
    success:function(data){ 
     //alert(data); 
      } 
}); 

在控制檯響應:

enter image description here

回答

0

我只是忽略Jquer y Ajax,並通過Html::a做了兩個動作。當我在標籤中調用url時,文件被下載。並且還在控制器中做了一些更改。

瀏覽:

<?=Html::a('Create Zip',['site/zipdownload'],['class'=>'btn btn-danger pull-left'])?> 
<?=Html::a('Download',['site/download'],['class'=>'btn btn-danger pull-left'])?> 

控制器:

public function actionZipdownload(){ 

     $files = Yii::$app->request->post('img_src'); 

     $zip = new \ZipArchive(); 

     $tmp_file = 'uploads/images.zip'; 

     if(file_exists($tmp_file)){ 
      $zip->open($tmp_file, ZipArchive::OVERWRITE); 
     } 
     else{ 
      $zip->open($tmp_file, ZipArchive::CREATE); 
     } 
     $i=1; 

     foreach ($files as $file) { 
      $download_file = file_get_contents($file); 

      $fileParts = pathinfo($file); 
      $filename = $i.explode("?",$fileParts['filename'])[0]; 
      $zip->addFromString($filename, $download_file); 
      $i++; 
     } 

     $zip->close(); 
    } 

    public function actionDownload(){ 
     $path = 'uploads/images.zip'; 
     if(file_exists($path)){ 
     \Yii::$app->response->sendFile($path)->send(); 
     unlink($path); 
     } 
     else{ 
      return $this->redirect(['site/dashboard']); 
     } 
    }