skip to Main Content

The method create a zip file and download it.The file is created inside storage/app/public folder (I ran php artisan storage:link to create a symlinks) but it doesn’t download.

public function download()
{
    $zip_file = 'screenshots.zip';
    $zip_path = storage_path('app/public/'.$zip_file);
    $zip = new ZipArchive();
    $zip->open($zip_path, ZipArchive::CREATE | ZipArchive::OVERWRITE);

    $path = storage_path('app/public/screenshots');
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
    foreach ($files as $name => $file) {
        if ($file->isDir()) {
            continue;
        }

        $filePath = $file->getRealPath();
        $relativePath = 'screenshots/' . substr($filePath, strlen($path) + 1);
        $zip->addFile($filePath, $relativePath);
    }

    $zip->close();

    return response()->download($zip_path);
}

JS

function downloadImages() {
    const token = document.querySelector('meta[name="csrf-token"]').content;

    fetch('/download', {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json, text-plain, */*',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': token
        },
        method: 'get',
    })
        .then((response) => {
            console.log('download');
        })
        .catch((error) => {
            console.log(error);
        })
}

2

Answers


  1. Chosen as BEST ANSWER

    Fixed! The APP_URL was not set correctly.

    I also changed the JS method to:

    function downloadImages() {
      window.location = '/download';
    }
    

    Thanks @pathum-bandara


  2. For cross-platform download at client browser, You can use php echo string:

    echo "Here is your download link: " . "<a id="photos_collection" href='". $zip_path ."' download='". $zip_file ."'>". $zip_file . " (" . filesize_formatted($zip_path) . ")" ."</a>";
    

    Js
    r is a div for receiving response as responseText:

    $("#r").html(this.responseText); $("#photos_collection").click();
    
    
    $("#r").html(response); $("#photos_collection").click();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search