Rails-如何从控制器发送图像 [英] Rails - How to send an image from a controller

查看:54
本文介绍了Rails-如何从控制器发送图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

in my rails app, I need to pass back a image.

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

I have a 1x1.gif tracking pixel in my route as follows:

 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

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

The problem is that for some reason sometimes this times outs. with the following error:

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并通过网络调用将其回传到我自己的服务器上?

Any ideas on how I can pass this image that's stored locally, versus having to use open and make a web call back to my own server?

谢谢

推荐答案

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

Is there a reason that you cannot save the file to public/_ctrack.gif, remove the route, and let the underlying web server serve the image?

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

If you need to process the image from disk, just use open on the local filename:

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

rb将文件设置为openbinary模式.

The rb sets the file to open and binary modes.

这篇关于Rails-如何从控制器发送图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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