【发布时间】:2012-02-26 15:32:12
【问题描述】:
如何显示存储在项目目录之外的图像?
有简单的方法吗?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 html-helper
如何显示存储在项目目录之外的图像?
有简单的方法吗?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 html-helper
我看到了两种方式:
http://yourapp.com/images/ 提供来自特定目录的文件。在 rails 中,使用传统的image_tag 显示图像
Nginx 示例:
# Find the right `server` section which you currently use to serve your rails app
server {
listen 80;
# Add this
location /images {
root /var/www/my/specific/folder;
}
location / {
#...
#... Here you should already some code to proxy to your rails server
}
}
With that, when you access to `yourserver.com/images`, nginx serve your specific folder and not your rails app. Then in your app view :
<%= image_tag 'http://yourserver.com/images/my_pic.jpg' %>
如果您无法访问您的服务器设置,您可以使用 send_file 提供来自控制器操作的图像文件
在控制器中:
class ImagesController < ApplicationController
def show
send_file File.join('/var/www/my/specific/folder',params[:name]), :disposition => 'inline'
end
end
在config/routes.rb
match '/images/:name' => 'images#show', :as => :custom_image
然后,当您访问此操作时(通过您在config/routes.rb 中定义的路线),您就有了图像。所以在你看来,你用这个 URL 做一个传统的image_tag:
<%= image_tag custom_image_path( 'my_pic.jpg' ) %>
OR
<%= image_tag custom_image_url( 'my_pic.jpg' ) %>
【讨论】:
如果它存储在 Rails 应用目录之外,那么它不属于资产管道,您可以简单地链接到它:
<%= image_tag("http://example.com/some_file.jpg") %>
显然它必须可以通过 HTTP 访问(您需要安装 nginx 或 Apache 服务器)。
【讨论】:
这可能是个坏主意,会导致很多问题。一些安全性,一些功能,但大多数效果我实际上不知道。
根据经验,我确实知道,每当您违反约定关于东西在哪里和在哪里的问题时,这是一个滑坡,最好避免。
使用提供的框架创建解决方案。
请注意,如果您使用的是 rails 3.1+ 而不是
【讨论】: