在这里,我无法下载任何Zip文件。这段代码也在创建Zip,但我无法下载。请知道WordPress / PHP Guru的任何人帮助我。
此自定义JS将数据传递给img_zip
,而img_zip()
函数可以使用图像及其度假村名称来调用zipDownload
函数。 zipDownload()
也有一个图像数组和度假村名称,但我认为也创建了Zip。在响应时,我无法下载Zip文件。请引导我。
.php
<button type="button" class="cart-detail select-and-download" data-resortname ="<?php echo $resort_title ?>" data-type="<?php echo $resort_type ?>" data-postid="<?php echo get_the_ID() ?>" data-keyword="<?php echo $resort_data[$keyword_field] ?>" data-toggle="collapse" aria-expanded="false" aria-controls="collapseExample" >
Download
</button>
custom.js
$('.select-and-download').click(function () {
params = [];
postid = $(this).data('postid');
keyword = $(this).data('keyword');
type = $(this).data('type');
resort = $(this).data('resort');
resort_name = $(this).data('resortname');
let selectedValues = getValueUsingClass();
data = {
action: 'img_zip',
resort_name : resort_name,
postid: postid,
selectedValues: selectedValues,
keyword: keyword,
type: type,
};
$.ajax({
url: ajaxurl,
type: 'POST',
data: data,
success: function (response) {
console.log(response);
},
});
});
});
Function.php
function img_zip() {
$resort_name = $_REQUEST['resort_name'];
$images = $_POST['selectedValues'];
zipDownload($images,$resort_name);
}
function zipDownload($files, $resort_name)
{
// var_dump($files); // all images in array
// var_dump($resort_name); // resort name
ini_set('memory_limit','20048M');
$zip = new ZipArchive;
$zipName = $resort_name.'_'.date("d_m_Y").'_'.get_current_user_id().'.zip';
$filename = get_template_directory().'/downloads/'.$zipName;
// die($filename);
if ($zip->open($filename, ZipArchive::CREATE) === TRUE)
{
foreach ($files as $file) {
// echo $file; //here i am get image url
$zip->addFromString(basename($file),file_get_contents($file, FILE_USE_INCLUDE_PATH));
}
$zip->close();
}
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=" . $zipName);
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
unlink($filename);
echo $filename;
}
答案 0 :(得分:0)
您无法使用ajax触发下载,但可以存档所需内容,将。$ ajax调用替换为:
var downloadForm = $('<form method="post" action="' + ajaxurl + '">');
downloadForm.append('<input type="hidden" name="action" value="img_zip" />');
downloadForm.append('<input type="hidden" name="resort_name" value="' + resort_name + '" />');
downloadForm.append('<input type="hidden" name="postid" value="' + postid + '" />');
downloadForm.append('<input type="hidden" name="keyword" value="' + keyword + '" />');
downloadForm.append('<input type="hidden" name="type" value="' + type + '" />');
downloadForm.appendTo('body');
downloadForm.submit();
downloadForm.remove();