在Yii2

时间:2017-07-31 07:10:42

标签: php jquery yii2 zip

我正在尝试下载包含许多图像的zip文件。当我在浏览器中调用路径但是当我从Jquery ajax调用时没有下载时,此代码正常工作。需要在标题中更改或添加任何内容吗?请帮助。

控制器:

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

1 个答案:

答案 0 :(得分:0)

我只是忽略了Jquery 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']);
        }
    }