Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Is it possible to give external image a local url?

Because it is not possible to uploade files to a Heroku app.

I am using a Amazon S3 storage server for images.

The problem is just that the image url is to the Amazon S3 server.

I would like it to be mydomain.com/myimage.png instead of s3.amazon.com/bucket/myimage.png

How is it possible to show a image on a amazon s3 server when visiting example: mydomain.com/myimage.png ?

like image 819
Rails beginner Avatar asked Dec 28 '22 03:12

Rails beginner


2 Answers

My solution, I only use png images:

In routes:

match "/images/vind/:style/:id/:basename.png" => "public#image_proxy"

In public controller:

def image_proxy
  image_url = "http://s3-eu-west-1.amazonaws.com/konkurrencerher#{request.path}"
  response.headers['Cache-Control'] = "public, max-age=#{84.hours.to_i}"
  response.headers['Content-Type'] = 'image/png'
  response.headers['Content-Disposition'] = 'inline'
  render :text => open(image_url, "rb").read,
end
like image 86
Rails beginner Avatar answered Jan 06 '23 22:01

Rails beginner


You can create a rack middleware that will look for a pattern in the url (/images/* or *.png) and when there's a match, it will act as a proxy, requesting the image from S3 and serving the content that it receives.

Make sure you set the caching headers right, so that Heroku's reverse proxy will cache it and serve it quickly.

like image 41
Leventix Avatar answered Jan 06 '23 23:01

Leventix