19

在我的 Rails 应用程序中,我需要传回一张图片。

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

 match "/_ctrack.gif" => "email_tracking_pixels#my_method"

在控制器中:

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

问题是由于某种原因有时会超时。出现以下错误:

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'

关于如何传递存储在本地的这个图像,而不是必须使用 open 并将网络调用回我自己的服务器的任何想法?

谢谢

4

2 回答 2

48

改用 send_file 不是更好吗?

send_file Rails.root.join("public", "file.gif"), type: "image/gif", disposition: "inline"
于 2012-02-21T19:23:42.627 回答
17

是否存在无法将文件保存到public/_ctrack.gif、删除路由并让底层 Web 服务器提供图像的原因?

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

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

rb文件设置为openbinary模式。

于 2011-03-08T04:14:09.143 回答