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

不问归期 提交于 2019-12-10 15:45:55

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/20275841/sinatra-how-to-respond-with-an-image-with-headers-content-type-image-jpeg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!