extjac's avatar

S3 Upload & Download

I am using S3 to upload and download files. The files needs to be private; they cant be public.

The below code actually works, but I was wondering whats the correct/better way to do the download?

# the upload codes looks something like this....

$file = request()->file('file_name');

$file_name = \Str::random(9) . $file->getClientOriginalName() );

$path = 'secure/files/' ;

\Storage::disk('s3')->put( $path.$file_name , file_get_contents($file)  ); //,  'public'

//Save file in in the DB

and the download codes looks like this

<?php

namespace App\Helpers;


class S3
{

	public function download()
	{

		request()->validate([
			'filename' =>'required',
			'path' =>'required',
		]);

	
		$path = request()->path;
		
		$filename = request()->filename;

		$file = \Storage::disk('s3')->get($path.$filename);

		$headers = [
		    'Content-Type' => 'text/csv', 
		    'Content-Description' => 'File Transfer',
		    'Content-Disposition' => "attachment; filename={$filename}",
		    'filename'=> '{$filename}'
		];

		return response( $file, 200, $headers );

	}


}

Download route looks like this

Route::get('/download', '\App\Helpers\S3@download')->middleware('auth');

and use it like this

<a  href="{{ url("download?filename={$file->name}&path={$file->path}") }}" > Open </a>
0 likes
4 replies
chaudigv's avatar

If you simply open the path_link on your browser, can you view the file? If yes, then your s3 is public.

If you have proper configurations set on AWS IAM, then only the project with your AWS KEY_ID and SECRET will be authorized to view and download the file.

extjac's avatar

currently you cant open it with just the url. You need to use the download route to do so. But i am not happy with the code. I am hopping there is better way to do it.

extjac's avatar
extjac
OP
Best Answer
Level 6

tried this and it worked

	public function download()
	{

		request()->validate([
			'filename' =>'required',
			'path' =>'required',
		]);

	
		$path = request()->path;
		
		$filename = request()->filename;
		
		return \Storage::disk('s3')->download($path.$filename);

	}

Please or to participate in this conversation.