2017-07-31 13 views
0

私は多くのimages.Thisコードで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を実行し、2つのアクションを持つ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']); 
     } 
    } 
関連する問題