Laravel AWS S3 Image Streaming view

725 views Asked by At

How can I get AWS S3 image as streaming view?

Now I can see image as following url:

<img src="https://s3.us-east-1.amazonaws.com/my-bucket/image.png" />

I want to get like this:

<img src="https://myproject.com/upload/image.png" />

I tried as following but it didn't work. My route:

Route::get('/upload/{path_to_image}', 'FileController@getImage')->where('path', '(.*)');

-My Controller

    public function getImage($disk, $path)
    {
        $headers = array(
            'Content-Type: application/image',
        );
        if(Storage::disk("s3")->exists($path))
        {
            $file = Storage::disk("s3")->path($path);
            return response()->file($file, $headers);
        }
        abort(404);
    }

Any suggestion would be appreciated!

1

There are 1 answers

0
amsh On BEST ANSWER

This solution is based on AWS.

Use CloudFront (CDN) with custom domain name to use your own url in place of S3 URL.

  • Create a CloudFront distribution and attach it to your S3 bucket.
  • Allow only HTTPS requests in Viewer Protocol Policy.
  • For alternate domain names (CNAMEs) type your custom domain.
  • Provide the SSL Certificate for your domain.

You can follow this article for detailed steps.

Once the distribution is available, you can access S3 files with your domain url, e.g. https://s3.us-east-1.amazonaws.com/my-bucket/path/to/image.png can be accessed as https://myproject.com/image.png.

If you want to use some custom path for images, e.g. /upload/image.png you can use a Behaviour and specify that path.

Please read this article to know more about CloudFront and how it can optimize your web responses.