I'm trying to write a script to download a file. But when I click "Download" nothing happens. I'm using Laravel for my project. This is the function:
public function downloadUserFile(){
$userid = Auth::id();
$result = $_POST['filename'];
$query = File::where('filename', $result)->where('userid', $userid)->get();
foreach($query as $queryResult){
$mimeType = $queryResult->mimetype;
$filepath = $queryResult->filePath;
$filesize = $queryResult->filesize;
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $filesize);
ob_clean();
flush();
readfile($filepath);
exit;
}
}
}
And the ajax:
if(key === "download") {
var classElements = document.querySelectorAll("tr.ui-selected td.filename");
var csrf = $('input[name=_token]').val();
for(var x = 0;x < classElements.length;x++){
var result;
result = classElements[x].innerHTML;
$.ajax({
async: true,
method: 'POST',
url: '../public/downloadfile',
data: { filename: result, "_token": csrf }
});
};
}
The ajax response and the PHP don't give me errors and I can't understand why nothing actually happens. What could be the problem?