Sinatra:如何响应带有标题“ content-type”的图像=> “图片/ jpeg” [英] Sinatra: How to respond with an image with headers "content-type" => "image/jpeg"

查看:89
本文介绍了Sinatra:如何响应带有标题“ content-type”的图像=> “图片/ jpeg”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

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.

我将如何处理

注意:
指向图像的链接不是秘密的(因为它托管在S3上)。它用于生成标识的站点。

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

结帐 http://identico.in/[insert_any_key_here]。原因是我希望服务器进行查找,如果映像已存在于S3上,则使用该映像,如果不存在,则生成一个映像,然后将其上传到s3。

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.

推荐答案

是的,如果要从您的服务器发送,您需要先将其放在服务器上,然后再发送。因此,大多数时候您需要使用 send_file open('link')并成为存储服务器和客户端的代理。

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

但是,如果链接不是秘密,您可以渲染一些JavaScript,它将在浏览器中打开图像

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

这篇关于Sinatra:如何响应带有标题“ content-type”的图像=&gt; “图片/ jpeg”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆