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
Fixed! The
APP_URL
was not set correctly.I also changed the JS method to:
Thanks @pathum-bandara
For cross-platform download at client browser, You can use php echo string:
Js
r is a div for receiving response as responseText: