I am trying to use AJAX & PHP Function for downloading a file. my goal is to use AJAX for sending variables from Datatable to PHP function. and PHP function will search for the file in my storage and download it.
It's not working. when I using the URL I can download the file. but when I trigger it with AJAX it's not working.
I want to create a PHP function that will receive file name and generate the download link for an HTML button. (which displayed in a data table)
Ajax:
//download button
$('#files').on('click', 'button#download',function (ref) {
var data = table.row($(this).parents('tr')).data();
var file_name=data.filename;
ref.preventDefault();
// alert(data.filename);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
datatype:'binary',
url: "/download?"+data.filename,
success: function(result){
console.log(result);
}
});
});
PHP:
public function getDownload(){
$tmpfile='1520001503b1.png';
$sd= DB::table('files')
->where('filename',$tmpfile)
->get();
$myFile = public_path("uploads/1520001503b1.png");
$headers = ['Content-Type: application/png'];
$newName = 'bla'.time().'.png';
return response()->download($myFile, $newName, $headers);
}
route:
Route::match(['get', 'post'], '/download','FilesController@getDownload');