определить заголовок в Ajax для генерации zip PHP - PullRequest
0 голосов
/ 25 сентября 2018

Я пытаюсь сгенерировать zip-файл с помощью ZipArchive Class, содержащий pdf-файл, сгенерированный тоже с помощью библиотеки FPDF.

Для этого я использую ajax и PHP, проблема в том, что я не знаю, как установить заголовки в ajax, чтобы принудительно загрузить их в браузере.Содержимое файла читается в моем HTML, а не отправляется обратно в zip-архив.

PHP-скрипт:

<?php
require('config/config.php');
require('fpdf/fpdf.php');

if(!isset($_SESSION))
{
    session_start();
}

$output = "";

if(isset($_SESSION['user']))
{
    $currentTime = time();
    if($currentTime < $_SESSION['expire'])
    {
        if(!empty($_POST['candidacy']))
        {
            $stmt = $cnx->prepare('SELECT * FROM candidacies WHERE id = :candidacy');
            $stmt->bindValue(':candidacy', $_POST['candidacy'], PDO::PARAM_INT);
            $stmt->execute();

            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            var_dump($result);
            foreach($result as $key => $value)
            {
                $nameUser = $value['lastName']." ".$value['firstName'];
                $emailUser = $value['email'];
            }

            $pdf = new FPDF();

            $pdf->AliasNbPages();
            $pdf->AddPage();

            $pdf->Image('img/candidacy.jpg',10,6,25);

            $pdf->SetFont('Times','',13);

            $pdf->Cell(60);
            $pdf->Cell(80,10, utf8_decode('Candidacy'),1,1,'C');
            $pdf->ln();

            $pdf->Cell(60);
            $pdf->Cell(80,10, date("d/m/Y"),1,1,'C');
            $pdf->ln();

            $pdf->Cell(50,10,'Nom complet : ', 0,0);
            $pdf->Cell(65,10, utf8_decode($nameUser), 0,1);

            $pdf->Cell(50,10, 'Email : ', 0,0);
            $pdf->Cell(100,10, utf8_decode($emailUser), 0,1);

            $file = 'CCandidacy-'.$nameUser.'.pdf';

            $pdf->Output('F', $file);

            if(extension_loaded('zip'))
            {
                $zip = new ZipArchive();

                $zip_name = md5(random_bytes(64)).".zip";

                if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
                {
                    $output .= "Impossible to create zip !";
                }

                $zip->addFile($file);

                $zip->close();

                if(file_exists($zip_name))
                {
                    header('Content-type: application/zip');
                    header('Content-Disposition: attachment; filename="'.$zip_name);
                    header('Content-Length: ' . filesize($zip_name));

                    readfile($zip_name);

                    unlink($zip_name);
                }
            }
            else
            {
                $output .= "Check extension !";
            }

            return $zip_name;
        }
    }
}
else
{
    unset($_SESSION['user']);
    session_destroy();
    header('Location: ../login.php');
    exit(0);
}

JS-скрипт:

function zipExtract(candidacy)
{
    var content = {};
    content['candidacy'] = candidacy;

    $.post('zipCandidacy.php', content, function(data)
    {
        location.href = data;
    });
}

Ответы [ 2 ]

0 голосов
/ 26 сентября 2018

Я наконец нашел решение!Как вы указали мне, Оливер, AJAX был не лучшим способом определить заголовок, как я хотел.Следовательно, когда выполняется событие onclick, я перенаправляю на страницу обработки php, чтобы перейти к загрузке zip-файла!

<?php
require('config/config.php');
require('fpdf/fpdf.php');

if(!isset($_SESSION))
{
    session_start();
}

$output = "";

if(isset($_SESSION['user']))
{
    $currentTime = time();
    if($currentTime < $_SESSION['expire'])
    {
        if(!empty($_GET['candidacy']))
        {
            $stmt = $cnx->prepare('SELECT * FROM candidacies WHERE id = :candidacy');
            $stmt->bindValue(':candidacy', $_GET['candidacy'], PDO::PARAM_INT);
            $stmt->execute();

            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach($result as $key => $value)
            {
                switch($value['zipcode'])
                {
                    case "North":
                        $zipcode = "Nord";
                        break;
                    case "South":
                        $zipcode = "Sud";
                        break;
                    case "East":
                        $zipcode = "Est";
                        break;
                    case "West":
                        $zipcode = "Ouest";
                        break;
                }

                switch($value['transportMeans'])
                {
                    case "onFoot":
                        $transportMeans = "À pied";
                        break;
                    case "vehicle":
                        $transportMeans = "Voiture";
                        break;
                    case "bike":
                        $transportMeans = "Moto";
                        break;
                    case "bus":
                        $transportMeans = "Bus";
                        break;
                    case "carpool":
                        $transportMeans = "Covoiturage";
                        break;
                    case "bicycle":
                        $transportMeans = "Vélo";
                        break;
                }

                switch($value['candidacyType'])
                {
                    case "mysteryCustomer":
                        $candidacyType = "Client Mystère";
                        break;
                    case "investigationUnit":
                        $candidacyType = "Chargé d'enquêtes";
                        break;
                    case "investigators":
                        $candidacyType = "Enquêteurs/Enquêtrices";
                        break;
                }

                $nameUser = $value['lastName']." ".$value['firstName'];
                $age = $value['age'];
                $employment = $value['employment'];
                $zipcode = $zipcode;
                $transportMeans = $transportMeans;
                $scheduleRange = $value['scheduleRange'];
                $emailUser = $value['email'];
                $phoneNumber = $value['phoneNumber'];
                $candidacyType = $candidacyType;
                $coveringLetter = $value['coveringLetter'];
                $curriculumVitae = $value['curriculumVitae'];
                $createdAt = $value['createdAt'];
            }

            $pdf = new FPDF();

            $pdf->AliasNbPages();
            $pdf->AddPage();

            $pdf->Image('img/candidacy.jpg',10,6,25);

            $pdf->SetFont('Times','',13);

            $pdf->Cell(60);
            $pdf->Cell(80,10, utf8_decode('Candidature'),1,1,'C');
            $pdf->ln();

            $pdf->Cell(60);
            $pdf->Cell(80,10, $createdAt,1,1,'C');
            $pdf->ln();

            $pdf->Cell(50,10, 'Nom complet : ', 0,0);
            $pdf->Cell(65,10, utf8_decode($nameUser), 0,1);

            $pdf->Cell(50,10, utf8_decode('Âge : '),0,0);
            $pdf->Cell(65,10, utf8_decode($age), 0,1);

            $pdf->Cell(50,10,'Profession : ',0,0);
            $pdf->Cell(65,10, utf8_decode($employment), 0,1);

            $pdf->Cell(50,10, 'Secteur : ',0,0);
            $pdf->Cell(65,10, utf8_decode($zipcode), 0,1);

            $pdf->Cell(50,10, 'Moyen de transport :',0,0);
            $pdf->Cell(65,10, utf8_decode($transportMeans), 0,1);

            $pdf->Cell(50,10, 'Horaires : ',0,0);
            $pdf->Cell(65,10, utf8_decode($scheduleRange), 0,1);

            $pdf->Cell(50,10, 'Email : ', 0,0);
            $pdf->Cell(100,10, utf8_decode($emailUser), 0,1);

            $pdf->Cell(50,10, utf8_decode('N° de téléphone : '),0,0);
            $pdf->Cell(65,10, utf8_decode($phoneNumber), 0,1);

            $pdf->Cell(50,10, 'Candidature : ',0,0);
            $pdf->Cell(65,10, utf8_decode($candidacyType), 0,1);

            $file = 'Candidature-'.$nameUser.'.pdf';

            $pdf->Output('F', $file);

            $files = array($file, "candidatures/".$coveringLetter, "candidatures/".$curriculumVitae);

            if(extension_loaded('zip'))
            {
                $zip = new ZipArchive();

                $zip_name = md5(random_bytes(64)).".zip";

                if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
                {
                    $error .= "Création impossible du zip !";
                }

                foreach($files as $content)
                {
                    $zip->addFile($content);
                }

                $zip->close();

                if(file_exists($zip_name))
                {
                    header('Content-Type: application/zip');
                    header('Content-Disposition: attachment; filename="'.$zip_name);
                    header('Content-Length: ' . filesize($zip_name));

                    readfile($zip_name);

                    unlink($zip_name);
                }
            }
            else
            {
                $error .= "Vérifier l'extension !";
            }

            $query = $cnx->prepare('UPDATE candidacies SET lastExport = now() WHERE id = :candidacy');
            $query->bindValue(':candidacy', $_GET['candidacy'], PDO::PARAM_INT);
            $query->execute();
        }
    }
}
else
{
    unset($_SESSION['user']);
    session_destroy();
    header('Location: ../login.php');
    exit(0);
}


function zipExtract(candidacy)
{
    window.location.href = ("../zipCandidacy.php?candidacy="+candidacy);
}
0 голосов
/ 25 сентября 2018

Вы можете просто перенаправить на сгенерированный zip-файл, используя location.href, как только вызов ajax будет готов (это будет означать, что ваш zip-файл тоже готов)

Возвращает URL-адрес zip-файла из вашего PHP, а затемпросто используйте ниже ...

function zipExtract(candidacy)
{
    var content = {};
    content['candidacy'] = candidacy;

    $.post('zipCandidacy.php', content, function(data)
    {
       location.href=data;
    });
}

Не думаю, что вам нужно ниже, но пишите их на всякий случай ...

Имейте в виду, вы неНе устанавливайте заголовки в ajax.Вы устанавливаете заголовки в своем php-файле, используя функцию header () http://php.net/manual/en/function.header.php

mime-тип для zip (или просто скачиваете, если сервер не может удовлетворить ваш zip-запрос)

application/zip, application/octet-stream

в коде PHP ..

// We'll be outputting a ZIP
header('Content-Type: application/zip, application/octet-stream');

// It will be called myzip.zip
header('Content-Disposition: attachment; filename="myzip.zip"');

// your PHP code and FPDF stuff
...