3

I am uploading files tos3 I want it to download securely using following code in my controller, but it's not working.

I am using Laravel 5.5 and files visibility is not public on s3.

if( Storage::disk('s3')->exists($file_path) ) {
      $file =  Storage::disk('s3')->get($file_path);
      return response()->download($file);
}

abort(404, 'File not found.');

It's giving me this error

is_file() expects parameter 1 to be a valid path, string given
...
/home/vagrant/spark-etr/vendor/symfony/http-foundation/File/File.php:36
#1 /home/vagrant/spark-etr/vendor/symfony/http-foundation/File/File.php(36): is_file('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...')
#2 /home/vagrant/spark-etr/vendor/symfony/http-foundation/BinaryFileResponse.php(94): Symfony\\Component\\HttpFoundation\\File\\File->__construct('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...')
#3 /home/vagrant/spark-etr/vendor/symfony/http-foundation/BinaryFileResponse.php(53): Symfony\\Component\\HttpFoundation\\BinaryFileResponse->setFile('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...', 'attachment', false, true)
#4 /home/vagrant/spark-etr/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php(125): Symfony\\Component\\HttpFoundation\\BinaryFileResponse->__construct('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...', 200, Array, true, 'attachment')

The file is on s3 since I am checking for exists before downloading.

Update

Dumping the $file var gives me binary like this

enter image description here

Please help

Saqueib
  • 3,484
  • 3
  • 33
  • 56

2 Answers2

5

Try

if( Storage::disk('s3')->exists($file_path) ) {
      $file =  Storage::disk('s3')->get($file_path);

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

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

Update

You can read more about downloading large files Why don't large files download easily in Laravel?

Norris Oduro
  • 1,019
  • 8
  • 17
2

Build the response yourself:

    $file = ''; // what you got from S3
    $mimeType = 'text/plain'; // or whatever the mime type is
    $fileName = 'example.txt';

    $headers = [
        'Content-type'        => $mimeType,
        'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
        'Content-Length'      => sizeof($file),
    ];

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

... or research on how to download streams.

ipalaus
  • 2,253
  • 4
  • 27
  • 42