ackerchez
ackerchez

Reputation: 1756

Laravel Download from S3 To Local

I am trying to download a file that I stored on S3 to my local Laravel installation to manipulate it. Would appreciate some help.

I have the config data set up correctly because I am able to upload it without any trouble. I am saving it in S3 with following pattern "user->id / media->id.mp3" --> note the fact that I am not just dumping files on S3, I am saving them in directories.

After successfully uploading the file to S3 I update the save path in my DB to show "user->id / media->id.mp3", not some long public url (is that wrong)?

When I later go back to try and download the file I am getting a FileNotFoundException at S3. I'm doing this.

$audio = Storage::disk('s3')->get($media->location);

The weird thing is that in the exception it shows the resource that it cannot fetch but when I place that same url in a browser it displays the file without any trouble at all. Why can't the file system get the file?

I have tried to do a "has" check before the "get" and the has check comes up false.

Do I need to save the full public URL in the database for this to work? I tried that and it didn't help. I feel like I am missing something very simple and it is making me crazy!!

Upvotes: 12

Views: 30180

Answers (3)

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41430

Say, you have AWS S3 as your default storage.

And you want to download my_file.txt from S3 to my_laravel_project\storage\app\my_file.txt

And you want to make it a one-liner

Storage::disk('local')->put('my_file.txt', Storage::get('my_file.txt'));

Upvotes: 1

Shahrukh Anwar
Shahrukh Anwar

Reputation: 2632

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);

Upvotes: 1

Chintan7027
Chintan7027

Reputation: 7615

Late answer but important for others,

 $s3_file = Storage::disk('s3')->get(request()->file);
 $s3 = Storage::disk('public');
 $s3->put("./file_name.tif", $s3_file);

The response of $s3_file will be a stream, you can save that stream data to file using Laravel put file method, you will find this stream file in storage/public directory.

Upvotes: 21

Related Questions