Загрузка файлов из файла PHP в Ajax;Файлы не загружаются - PullRequest
0 голосов
/ 14 июня 2019

У меня есть галерея файлов в таблице с флажками для каждого файла.Цель состоит в том, чтобы проверить файлы, которые вы хотите загрузить, а затем нажать кнопку, чтобы загрузить ZIP-файл, содержащий эти отдельные файлы.

Кажется, все работает нормально ... массив, ajax, ответ "success" ... но файл не загружается.Возможно ли скачивать файлы таким способом?Если нет, что мне нужно сделать по-другому, чтобы это работало правильно?

jQuery

// searchIDs returns an array of file names. ie:
// 'file1.zip', 'file2.png', 'file3.pdf'

$('#toolkit-bin input[type=submit]').on('click', function(e) {
    e.preventDefault();

    $.ajax({
        type : 'POST',
        url : './functions.php',
        data : { searchIDs: searchIDs },
        success : function(data) {
            alert(data);
        },
        error : function(request,error) {
            alert("Request: "+JSON.stringify(request));
        }
    });

});

functions.php

// ROOT is defined as the root directory of the server.

$zipname = 'LiveLOUD-Toolkit.zip';
$zip = new ZipArchive();
$zip -> open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Get the array of the selected files. 
$files = $_POST['searchIDs'];

// Loop through the files.
foreach ($files as $file)
{
    // Get the path to the file.
    $path = ROOT.'/_assets/toolkit/'.$file;

    // Add the file to the zip.
    $zip -> addFromString(basename($path), file_get_contents($path));  
}

// Zip archive will be created only after closing object.
$zip -> close();

// If the file was created successfully...
if (file_exists($zipname))
{   
    // Download the zip file.
    // THIS STUFF DOES NOT SEEM TO WORK
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: '.filesize($zipname));

    // Delete the zip after download.
    unlink($zipname);

    // This is successfully returned.
    echo 'Success!';
}
else
{
    echo 'Error!';
}

1 Ответ

0 голосов
/ 17 июня 2019

Большое спасибо msg и людям в этой теме .Я загрузил свои загрузки, создав zip-файл в functions.php и передав имя файла обратно в ajax.Затем, используя window.location, откройте почтовый индекс.Мой окончательный код ниже:

jQuery / Ajax:

// searchIDs returns an array of file names. ie:
// 'file1.zip', 'file2.png', 'file3.pdf'

// If submmit download button is clicked...
$('#toolkit-bin input[type=submit]').on('click', function(e) {
    e.preventDefault();

    var searchIDs = [];

    $('#croud-toolkit').find(':checkbox:checked').map(function(){
        searchIDs.push($(this).val());
    });

    $.ajax({
        type : 'POST',
        url : './functions.php',
        data : { searchIDs: searchIDs },
        success : function(data) {
            window.location = './'+data;
        },
        error : function(data) {
            alert('error');
        }
    });

});

functions.php

// ROOT is defined as the root directory of the server.

// Name and create the Zip archive.
$zipname = 'LiveLOUD-Toolkit.zip';
$zip = new ZipArchive();
$zip -> open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Get the array of the selected files. 
$files = $_POST['searchIDs'];

// Loop through the files.
foreach ($files as $file)
{
    // Get the path to the file.
    $path = ROOT.'/_assets/toolkit/'.$file;

    // Add the file to the zip.
    $zip -> addFromString(basename($path), file_get_contents($path));  
}

// Zip archive will be created only after closing object.
$zip -> close();

// Return data to Ajax
echo $zipname;
...