[英]Zip file is not downloading in Yii2
I am trying to download the zip file with many images.This code is working when i call the path in browser but not downloading when i call from Jquery ajax.Need to change or add anything in header?please help. 我正在尝试下载包含许多图像的zip文件。当我在浏览器中调用路径时此代码有效,但是当我从Jquery ajax调用时无法下载。需要更改或添加标头中的任何内容吗?请帮助。
Controller: 控制器:
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 : jQuery的 :
$.ajax({
url:url+'site/zipdownload',
data:{'imgsrc':imgsrc},
type:'POST',
success:function(data){
//alert(data);
}
});
In console response: 在控制台响应中:
I just ignore the Jquery Ajax and done it by Html::a
with two actions..When i am calling the url in a tag then the file got downloaded.And also done some changes in controller. 我只是忽略了Jquery Ajax,并通过Html::a
进行了两个操作。当我在标签中调用url时,文件就被下载了。还对控制器做了一些更改。
Views: 浏览次数:
<?=Html::a('Create Zip',['site/zipdownload'],['class'=>'btn btn-danger pull-left'])?>
<?=Html::a('Download',['site/download'],['class'=>'btn btn-danger pull-left'])?>
Controller: 控制器:
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']);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.