This post is going to be about downloading files from the remote server via FTP mechanism in your Laravel application.
Let’s create a controller called DownloadController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Storage; use Response; class DownloadController extends Controller { function downloadFile(Request $request) { $file = $request->get('file'); if(!$file) { return Response::json('please provide valid path', 400); } $fileName = basename($file); $ftp = Storage::createFtpDriver([ 'host' => 'your_host', 'username' => 'your_ftp_user', 'password' => 'your_ftp_user_password', 'port' => '21', // your ftp port 'timeout' => '30', // timeout setting ]); $filecontent = $ftp->get($file); // read file content // download file. return Response::make($filecontent, '200', array( 'Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename="'.$fileName.'"' )); } } |
Now let’s inform about this controller to routes/web.php
1 |
That’s it. Now point your browser to http://yourhost.com/downloadFile?file=remote_path/fileName.png
.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
Exactly what I need. Thanks!
how to return to web view from remote ftp? not download.
just have to set proper headers. Or download them to local system and put in the web server.
Hi, how would i return all files in the ftp folder , not just one. Can you add that solution?
foreach( Storage::disk(‘ftp’)->glob(‘/’){
// do save code to location
}
I tried it but I got FileNotFoundException, while the file was uploaded to the ftp server and its name exists in $ftp->files().
I’m using Laravel 5.7
Instead of
return Response::make($filecontent, '200', array(
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment; filename="'.$fileName.'"'
));
is used this to store the downloaded file to disk:
Storage::drive("diskName")->put($storage_path . $fileName, $file_data);