1
votes

I want to download an excel file which stored into storage/export/ path. I used Maatwebsite excel provider for this in laravel 5.5.

My controller code is written below:

ob_end_clean();
ob_start();
Excel::create($excelName, function($excel) use($adminUserDataExcelSelected) {
$excel->sheet('Sheet 1', function($sheet) use($adminUserDataExcelSelected) {
$sheet->fromArray($adminUserDataExcelSelected);
});
})->store('xlsx');
ob_flush();
return response()->json(['path' => $path]);

My AJAX code is following;

$.ajax({
url: "/administrator/adminUser/exportselected/1/",
type:'POST',
data: {_token:_token, selected:selected, selectedField:selectedField},
success: function(data) { alert(data.path);
if($.isEmptyObject(data.error)){
}else{}
}
});

When I alert/ console.log the data.path, I received the below :

/var/www/html/stmd_OLD/storage/export/Admin-Users2018-05-17 04:46:47

My question is: How can instantly download the excel file now? Should I call another AJAX method here?

1

1 Answers

3
votes

You need to replace this line return response()->json(['path' => $path]); with this line

return response()->download(storage_path('storage/export/AdminUsers2018-05-17 04:46:47.xlsx'));

Then you just need to hit the link that calls the controller function that returns this. No need for extra AJAX call.

You may need to add this line at the start of the controller too

use Illuminate\Support\Facades\Storage;