So this should be pretty easy, yet I can’t get it work.
I have a controller method that finds an image based on a query, then the output gets cached. The image could be remote (flickr, google images, etc) or it could be local. Regardless of the source, I just need take the image file contents, and pass it through to the user. In essence, a proxy. Passing through remote images seems to work fine, but passing through local images gives me a:
invalid byte sequence in UTF-8
So here’s what I got. I’m hoping someone can solve the problem or guide me in a better direction with my code.
def image_proxy
query = params[:query]
image_url = get_image_url(query) # returns an absolute local file path or a URL
response.headers['Cache-Control'] = "public, max-age=#{12.hours.to_i}"
response.headers['Content-Type'] = 'image/jpeg'
response.headers['Content-Disposition'] = 'inline'
render :text => open(image_url).read
end
Remote files work fine, local files don’t.
Bonus to anyone that can help solve this other issue:
- I need to set the proper content type. Remote image urls don’t tell me the image type, I just get a url and sometimes the url doesn’t contain an extension. So I picked jpeg because it seems to work regardless of the image type sent to me.
Thanks!
Try using
render :text => open(image_url, "rb").read, which tells Ruby that the file it opens is binary, and not to try reading it as text.edit
For the bonus question, you could read the first few bytes and look at what they contain.
A PNG will always start with the hexadecimal byte values 89 50 4E 47 0D 0A 1A 0A (or the decimal values 137 80 78 71 13 10 26 10).
Wikipedia has a list of magic numbers used to identify file that you can look at. Just create a method of some sort that reads the first few bytes and compares it to that.