jeudi 18 août 2022

Downloading CSV File to User's Browser in Laravel 5.7 using response()->download() method Not Working

In my laravel application, a user clicks a download button, sending an ajax request to a download method in my controller. I get my data, convert it to a .csv file in a "public/csv" folder, and attempt to force the user's browser to download the file via the response()->download() method. The csv file is saving correctly in the directory, and if I console.log the response in my front-end, I get the csv data in my console as expected. However, the browser is not downloading the file.

The following is a portion of the controller method which contains the response that should be triggering the download. Is there something I am missing here?

foreach ($users as $key => $user) {
            if ($key == 0) {
                fputcsv($fp, array("User", "Email", "Company", "Region", "Primary Focus", "Role", "Logins", "Last Login", "Graphs Saved", "Reports Graphed", "Reports Graphed Count", "Images Exported", "PDFs Viewed", "PDFs Viewed Count", "Drawings Viewed", "Drawings Viewed Count", "Reports Downloaded", "Reports Downloaded Count", "Activities Total")); // email, phone, users_role_id, activated, data_standard, company_id, primary_focus, region, 
            }
            //Get additional stats on the user for output
            $companyName = $user['company'] ? html_entity_decode($user['company']->name) : "none";
            $regionName = $user['region'] ? $user['region']->name : "none";
            $roleName = $user['users_role'] ? $user['users_role']->name : "none";
            $primaryFocus =  $user->primaryFocus;  /*? $user->primaryFocus()->name : "none"; */
            fputcsv($fp, array($user["name"], $user['email'], $companyName, $regionName, $user['primary_focus_name'], $user['role_name'], $user['logins'], $user['last_seen'], $user['graph_saved'], $user['reports_graphed'], $user['reports_graphed_count'], $user['images_exported'], $user['pdfs_viewed'], $user['pdfs_viewed_count'], $user['drawings_viewed'], $user['drawings_viewed_count'], $user['reports_downloaded'], $user['reports_downloaded_count'], $user['activities_total']));
        }
        fclose($fp);
        //get headers for response so we can download file to user's browser
        $headers = ['Content-Description' => 'File Transfer', 'Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment;filename=' . basename($filePath)];
        // return ([$users, $filePath, basename($filePath), filesize($filePath), $headers]);
        return response()->download($filePath, basename($filePath), $headers);
    } ```


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire