我已经阅读了许多类似的问题,但是我找不到我的解决方案。
我需要做的是将POST变量中的文件压缩为数组,并获取刚刚创建的zip文件的路径。这是我的代码...我不断收到一个空对象,只是无法在其中创建1个文件
function downloadAllImages(){
$data = array();
$files = $_POST['files_to_download'];
$archive_file_name = 'images.zip';
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
$data['debug'].=("cannot open <$archive_file_name>\n");
}
//add each files of $file_name array to archive
foreach($files as $file)
{
$zip->addFile($file, basename($file));
}
$zip->close();
//then send the headers to foce download the zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
$data['debug'].=print_r($zip,true);
echo json_encode($data);
die();
}
压缩文件后,我正在使用JQuery获取下载链接。我只是无法将文件压缩。
[files_to_download数组打印:
Array(
[0] => http://localhost/br/wp-content/uploads/2020/04/rabbit-black-transp-300x300.png
[1] => http://localhost/br/wp-content/uploads/2020/04/bg-shop-300x169.png
)
还有我的jQuery
function downloadAllImages(){
var files_to_download = [];
$("img.downloadable").each(function(){
files_to_download.push($(this).attr('src'));
});
jQuery.ajax({
url: runAJAX.ajaxurl,
data: ({action: 'downloadAllImages', files_to_download:files_to_download}),
method: "POST",
success: function(data_received) {
displayAjaxResponse(data_received);
}
});
}
最后,我的一个朋友提供了帮助,PHP代码应如下所示:
function downloadAllImages()
{
$data = array();
$files = $_POST['files_to_download']; // array
$domain= wp_upload_dir();
// used this to rename the file so each post gets it's own zip
$prefix=$_POST['file_prefix'];
$zip = new ZipArchive();
$tmp_zip = $zip->open($domain['basedir'].'/'.$prefix.'images.zip', ZipArchive::CREATE);
foreach($filesas $img)
{
if(!empty($img))
{
$download_file = file_get_contents($img);
$zip->addFromString(basename($img), $download_file);
}
}
$zip->close();
$now = new DateTime();
$data['file'] = get_bloginfo('wpurl')."/wp-content/uploads/{$prefix}images.zip?v={$now ->getTimestamp()}";
echo json_encode($data);
die();
}
和jQuery看起来几乎一样,除了添加了'file_prefix'变量。