Hi
I've finally got my system downloading a file automatically, I had to re-write how I present the download option to the user - it's displayed in a VueJS component but allows the user to click the filename in a route so the code receives the location of the file and the filename.
My code now reads as follows:-
public function downloadFile($fileName, $location)
{
$variable = \IDHelpers::getID();
$ftp = Storage::createFtpDriver([
'host' => 'My FTP Server',
'username' => $this->ftp_username,
'password' => $this->ftp_password,
'port' => '21', // your ftp port
'timeout' => '30', // timeout setting
]);
// Set file path
$path_parts = [
config('tmp_folder'),
$variable->ID,
];
$destination_path = implode('/', $path_parts);
$destination = implode('/', [public_path(), $destination_path]);
// Ensure agency destination exists
\AppHelpers::makeDirectory($destination);
// Ensure the property destination exists
\AppHelpers::makeDirectory($destination.'/'.$location);
// get the file from the ftp server
$fileContents = ($ftp->get($location.'/'.$fileName));
//store it in the tmp destination
$localPath = $destination_path.'/'.$location;
$localFile = $destination_path.'/'.$location.'/'.$fileName;
$results = File::put($localFile, $fileContents);
//
// Initiate the download
//
$destination .= '/' . $location . '/' . $fileName;
//$file = Storage::get($localFile);
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . $fileName . "\"");
header("Content-Length: ".$results);
readfile($localFile);
return response()->file($localFile);
}
As I've had to rename stuff in the code for security, be assured the above code works as intended, I can get the file from the ftp location, put it in the tmp location on my server, the only bit that fails is the download, I suspect I've not got the header coded correctly as if I use FileZilla and download the file, it opens without issue, however, if I run the above and try to open the downloaded file, it fails.
Any idea on what setting I have that is incorrect?
Cheers
Carl.