繁体   English   中英

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

[英]Rails - How to send an image from a controller

在我的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'

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

谢谢

使用send_file不是更好吗?

send_file Rails.root.join("public", "file.gif"), type: "image/gif", disposition: "inline"

有没有理由不能将文件保存到public/_ctrack.gif ,删除路由,让底层Web服务器为图像服务?

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

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

rb将文件设置为openbinary模式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM