Skip to content
Advertisement

Return S3 private file as stream

I’m currently working on a route for a project that I need to get a specific file from S3, read its content, and return as a binary. I can’t just use the S3 file url, because it is private and it is intentional (we just don’t want the bucket files open).
But the problem is, I want to stream it in a new page to not have the need to download the file.
Service:

$file = $this->s3Provider->getFileContents(false); // gets the file binary
return $file;

Controller:

return response()->streamDownload(function() use($file) {
    echo $file; // streams data to download it, but I want just to show the file...
  }, $filename);

Advertisement

Answer

I thought you are using Laravel, if so then you could return your image like this:

return response($file, $filename, [
    'Content-Type' => 'image/png',
    'Content-Length' => filesize($file)
  ]);

Another way that I use to return image is:

    return response()->file($path, array('Content-Type'=>'image/jpg'));

Content-Type should be your image type (JPG, PNG, etc.).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement