how to download file from s3 disk in Laravel
What is AWS S3?
Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance. S3 helps you securely upload and download your data with SSL encrypted endpoints and provides multiple options for encrypting data at rest. Amazon S3 helps you get the most out of your data by making sure its storage safely available when needed and will scale as your needs grow.
Downloading the contents from S3 can be made easier using Laravel. Using the steps mentioned below, a file of any type(image, video, pdf) from Amazon S3, placed earlier in the downloads folder can be downloaded.
STEPS:
1. Make a route for downloading the file.
Route::post('/downloadFile/{mediaId}', 'DownloadController@downloadFile');
2. In HTML, make an anchor tag for route
<a href="/downloadFile/{{$response['id']}}"> Download File </a>
3. In a controller, make a function for downloading a file
public static function downloadFile(Request $request) { try { $s3Disk = Storage::disk('s3'); //object for initializing s3 disk $validator = Validator::make($request->all(), [ 'media_id' => 'required' //validator to require media id for downloading file ]); if ($validator->fails()) { return Redirect::back()->withErrors(['msg', $validator->errors()]); ], __('constants.BAD_REQUEST')); } // if media id is not available then validator gives error message $data = MediaLibrary::where([ 'id' => $request->media_id ])->first(); //get data from media library table according to media id from MediaLibrary modal $media_name = explode("/", $data->media_path); //explode media_path for media name $data->media_name = $media_name[2]; //assign name to $data object which is the 3rd element of array $media_path = $s3Disk->temporaryUrl($data->media_path, now()->addMinutes(30)); //make a temporaryUrl $data->media_path = $media_path; //assign that temporaryUrl in media path $media_links = array( 'media_path' => $data->media_path, 'media_name' => $data->media_name, 'file_type' => $data->file_type ); // make a array for path,name and file type //add headers for downloading file header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=" . $media_links['media_name']); header("Content-Type: " . $media_links['file_type']); return readfile($media_path); //to read file which is downloaded from headers } catch (\Exception $e) { return Redirect::back()->withErrors(['msg', 'Something went wrong. Kindly try after sometime.']); ], __('constants.INTERNAL_SERVER_ERROR')); } }