Rails - 如何从控制器发送图像

AnA*_*ice 18 open-uri ruby-on-rails ruby-on-rails-3

在我的rails应用程序中,我需要传回图像.

我的路线中有1x1.gif跟踪像素,如下所示:

 match "/_ctrack.gif" => "email_tracking_pixels#my_method"
Run Code Online (Sandbox Code Playgroud)

在控制器中:

def my_method
    send_data open('https://www.xxxxxx.com/images/1x1_transparent.gif') {|f| f.read }, :filename => '1x1_transparent.gif', :type => 'image/gif'
end
Run Code Online (Sandbox Code Playgroud)

问题在于,由于某些原因,有时会出现这种情况.出现以下错误:

2011-03-07T20:08:36-08:00 heroku[router]: Error H12 (Request timeout) -> GET www.xxxxxxx.com/images/1x1_transparent.gif dyno=web.1 queue=0 wait=0ms service=0ms bytes=0
2011-03-07T20:08:36-08:00 app[web.1]: 
2011-03-07T20:08:36-08:00 app[web.1]: OpenURI::HTTPError (503 Service Unavailable):
2011-03-07T20:08:36-08:00 app[web.1]:   app/controllers/email_tracking_pixels_controller.rb:19:in `my_method'
2011-03-07T20:08:36-08:00 app[web.1]:   lib/rack/www.rb:7:in `call'
Run Code Online (Sandbox Code Playgroud)

有关如何传递本地存储的图像的任何想法,而不是必须使用打开并将Web回调回我自己的服务器?

谢谢

Dav*_*les 44

使用send_file不是更好吗?

send_file Rails.root.join("public", "file.gif"), type: "image/gif", disposition: "inline"
Run Code Online (Sandbox Code Playgroud)

  • `send_file`是一个更好的选择,可以利用Web服务器中的X-SendFile或X-Accel-Redirect头来避免捆绑ruby进程. (2认同)

Mic*_*ley 16

是否有理由无法保存文件public/_ctrack.gif,删除路由,并让底层Web服务器提供图像?

如果需要从磁盘处理映像,只需使用open本地文件名:

send_data open("#{Rails.root}/path/to/file.gif", "rb") { |f| f.read } .......
Run Code Online (Sandbox Code Playgroud)

rb文件以套openbinary模式.