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);
})
}
CodePudding user response:
There could be several reasons why the download isn't working properly.
- One possible explanation is that the file path is incorrect. Check to ensure that the path to the zip file is correct and that the file is in the correct directory.
- Another possibility is that the download function is not properly configured. Make sure the function returns a response object, not a string, and that you pass the correct path to the download function, which in this case should be response()->download($zip path).
- If you're working on a web server, make sure it's set up to allow downloads and that the file's permissions are set correctly.
- If the file was not properly closed, another possibility exists. To rule this out, try calling $zip->close(); before the response.
You can try var dump the response to see if the function is returning anything to see if it can help you find the problem. You can also check the error log of your web server.
CodePudding user response:
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();