Невозможно сохранять файлы внутри ZIP с помощью ZipArchive - PullRequest
0 голосов
/ 07 мая 2020

Я читал много похожих проблем, но я просто не могу найти решение для своей.

Все, что мне нужно, это заархивировать файлы, которые входят в переменную 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);
        }
    }); 
}

1 Ответ

0 голосов
/ 08 мая 2020

В конце концов, мой друг помог, и код 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' .

...