squibby's avatar

How to upload/download files with s3?

Hi,

Struggling a little bit with downloading files from amazon s3 using laravel Storage.

Uploading a file is no problem:

Storage::disk('s3')->put($destination , file_get_contents($request->file),  'public'); 

But then when I want to download a file i am having difficulty.

$import = CsvImport::find($id);
$file = Storage::disk('s3')->get('uploads/csv/' .  $import->filename );
return Response::download($file , $import->filename);   

It is definitely returning the contents to the $file variable as I can log it, but how to make it downloadable? I am thinking I need to add some kind of headers to the file like this:

$headers = [
     'Content-Type' => 'text/csv', 
     'Content-Disposition' => 'attachment',
          'filename'=> $import->filename
 ];
return response()->download($file, $import->filename, $headers);

But I cannot get a download.

Has anyone any experience working with downloading file contents from s3?

Help most appreciated. Thanks

0 likes
2 replies
squibby's avatar
squibby
OP
Best Answer
Level 8

I got it working as follows:

$import = CsvImport::find($id);

$file = Storage::disk(config('filesystems.default'))->get('uploads/csv/' . $id . '/' . $import->filename );

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

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

1 like
Shahrukh4's avatar

You can give your Content-Type as desired and Content-Disposition as 'attachment' because your files are coming from S3 and you have to download it as an attachment.

$event_data = $this->ticket->where('user_id', $user_id)->first();
        
    $data  = $event_data->pdf;

    $get_ticket = 'tickets/'. $data;
    $file_name  = "YOUR_DESIRED_NAME.pdf";

    $headers = [
          'Content-Type'        => 'application/pdf',            
          'Content-Disposition' => 'attachment; filename="'. $file_name .'"',
    ];

    return \Response::make(Storage::disk('s3')->get($get_ticket), 200, $headers);
1 like

Please or to participate in this conversation.