msslgomez
1 month ago
167
5
Laravel

response->download working only sometimes

Posted 1 month ago by msslgomez

I'm trying to download a zip file from the server, sometimes it works and sometimes what gets downloaded is a getZip.html file that doesn't even exist I'm not sure why? I also noticed that sometimes the files doesn't get created but I don't get any errors and the if that checks if the file exists returns as true because all the file that go in the zip do get deleted. This is my code

public function getZip(Request $request)
    {
        $job_request = JobRequest::findOrFail($request->request_id);
        if ($job_request->user_id == auth()->user()->id) {
            $zip = new ZipArchive;

            if (true === ($zip->open('ReportesTodos-' . $request->request_id . '.zip',
                    ZipArchive::CREATE | ZipArchive::OVERWRITE))) {

                foreach ($job_request->reports as $report) {
                    if (Storage::disk('report_upload')->exists($report->report_name . '.xlsx')) {
                        $zip->addFile(public_path('reports\\' . $report->report_name . '.xlsx'),
                            $report->report_name . '.xlsx');
                    }
                }
                $zip->close();
            }

            if (File::exists(public_path('ReportesTodos-' . $request->request_id . '.zip'))) {
                foreach ($job_request->reports as $report) {
                    if (Storage::disk('report_upload')->exists($report->report_name . '.xlsx')) {
                       Storage::disk('report_upload')->delete($report->report_name . '.xlsx');
                    }
                }
            }
        }
        return response()->download(public_path('ReportesTodos-' . $request->request_id . '.zip'),
            'ReportesTodos-' . $request->request_id . '.zip');
    }

This is all working as expected excel the actual download and weirdly only sometimes, Ideally I would like to delete the .zip file after the user downloads it by adding ->deleteFileAfterSend(true) to my return but I'm scared that the file the user gets is that weird .html and then the actual .zip is gone. To get another zip is like a 10 min wait because it's a lot of files in there (over 100 excels).

How can I make sure the zip is the file that gets downloaded?

Please sign in or create an account to participate in this conversation.