繁体   English   中英

如何使用rails 3显示路径在Ruby on Rails项目目录之外的图像?

[英]How can I display an image whose path is outside my Ruby on Rails project directory using rails 3?

如何显示存储在项目目录外的图像?

有一个简单的方法吗?

我看到两种方式:

  • 在rails服务器之上,在生产环境中,有时在dev中,你必须使用像apache或nginx这样的web服务器。 有了这些,您可以为其他目录提供特定URL的文件。 EG你可以http://yourapp.com/images/提供特定目录中的文件。 在rails中,使用traditionnal 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执行traditionnal 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+而不是<= 3.0,则此功能也会受到影响,因为资产编译将js,css和图像复制到公共区域。

暂无
暂无

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

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