mercredi 26 septembre 2018

How to download a file over an ajax call in laravel

I have a ajax call, using axios to get a route that leads to a function looking like this:

public function excel(Request $request) {
        $items = $this->getApiResponse($request);
        $items = $this->transform($items->get());

        $createTmlReport = new CreateTmlReport($items);
        $report          = $createTmlReport->setColumnTitles([
            'Organization',
            'Business Unit',
            'Location',
            'Group LSD',
            'Equipment LSD',
            'Point',
            'Nominal Thickness',
            'Low Nominal Thickness (in)',
            'Current Thickness (in)',
            'Previous Thickness (in)',
            'PHH Shutdown (psi)',
            'Corrosion_rate (in/yr)',
            'Old Inspection Interval',
            'Inspection Interval',
            'Remaining Life (years)',
            'Last Inspection Date',
            'Next Inspection Date',
            'Estimated Repair Date',
            'Comments',
        ])->createReport();

        if (!file_exists(storage_path('app/excel/tml/reports/'))) {
            Storage::disk('local')->makeDirectory('excel/tml/reports');
        }

        $report->save(storage_path('app/excel/tml/reports/') . 'tml_report.xlsx');

        $headers = [
            'Content-Type: application/vnd.ms-excel',
            'Content-Disposition: attachment;filename="part_template.xls',
            'Cache-Control: max-age=0'
        ];

        return response()->download(storage_path('app/excel/tml/reports/tml_report.xlsx'), 'tml_report.xlsx', $headers);
    }

At the end of the function I return the response, if this was a regular route access any other way I would get the file, it would download, but since it's an API route, I get:

UEsDBBQAAgAIAGOCOk1HkkSyWAEAAPAEAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbK2UTU7DMBCF95wi8hYlblkghJp2QWEJlSgHMPakserYlmf6d3smaQsIiUDVbmJ....

I have no idea why I am getting a very long string back in the response instead of a file download. Is there something I am suppose to do on the javascript side to download the file when the response comes back?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire