samol
samol

Reputation: 20580

Sinatra: How to respond with an image with headers "content-type" => "image/jpeg"

Example:

require 'sinatra'

get '/somekey' do
  headers('Content-Type' => "image/jpeg")
  ["http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg", "http://img.brothersoft.com/screenshots/softimage/j/jpeg_converter-4567-1.jpeg"].sample
end

I want to respond with an image that is not hosted on my server.

How would I get about this?

Note: The link to the image is not secret (as it is hosted on S3). It is for a site that generates identicons.

Checkout http://identico.in/[insert_any_key_here]. The reason is I wanted the server to do a look up, if the image already exists on S3, use that one, if not, generate one and then upload it to s3.

Note: If I did:

require "open-uri"
open ["http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg", "http://img.brothersoft.com/screenshots/softimage/j/jpeg_converter-4567-1.jpeg"].sample

Then it works, however, I feel that this might be a lot slower because my server first has to download the image and open it and then the user has to download the image from my server.

Upvotes: 4

Views: 2013

Answers (1)

Ivan Shamatov
Ivan Shamatov

Reputation: 1416

yes, if you want to send from your server, you need to have it on your server before sending. So most of the time you need to use send_file open('link') and be a proxy from storage server and a client.

require 'sinatra'
require 'open-uri'

get '/' do
  send_file open('http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg'),
        type: 'image/jpeg',
        disposition: 'inline'
end

But if a link is not a secret, you can just render some javascript and it will open image in browser.

require 'sinatra'
get '/' do
  "<script>document.location = 'http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg'</script>
end

Upvotes: 6

Related Questions