【问题标题】:How can I display an image whose path is outside my Ruby on Rails project directory using rails 3?如何使用 rails 3 显示路径在我的 Ruby on Rails 项目目录之外的图像?
【发布时间】:2012-02-26 15:32:12
【问题描述】:

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

有简单的方法吗?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 html-helper


    【解决方案1】:

    我看到了两种方式:

    • 在您的 Rails 服务器之上,在生产环境中,有时在开发环境中,您必须使用像 apache 或 nginx 这样的 Web 服务器。有了这些,您可以为特定 URL 提供其他目录中的文件。例如。您可以让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' ) %>
      

    【讨论】:

    • 查看我的编辑。我将向您展示如何将它与自定义命名路由一起使用。
    • AFAIK,没有。在 rails 范围内,您必须遵循 rails 堆栈。但是控制器是在大约 30 年代创建的……如果需要,您可以将操作集成到另一个控制器中。我宁愿建议您查看第一个解决方案:即使现在在开发中您的应用程序顶部没有 Web 服务器,但在生产中您会有,所以您最好花时间学习如何配置它(在 apache 上创建一个虚拟主机或在 nginx 中创建一个新服务器......)
    • 我尝试了第一个,使用 nginx 服务器但无法加载给定的 url。
    【解决方案2】:

    如果它存储在 Rails 应用目录之外,那么它不属于资产管道,您可以简单地链接到它:

    <%= image_tag("http://example.com/some_file.jpg") %>
    

    显然它必须可以通过 HTTP 访问(您需要安装 nginx 或 Apache 服务器)。

    【讨论】:

    • 那么您是如何在生产中使用您的应用程序的?你只是在 80 端口上运行 Mongrel 吗?
    【解决方案3】:

    这可能是个坏主意,会导致很多问题。一些安全性,一些功能,但大多数效果我实际上不知道。
    根据经验,我确实知道,每当您违反约定关于东西在哪里和在哪里的问题时,这是一个滑坡,最好避免。

    使用提供的框架创建解决方案。

    请注意,如果您使用的是 rails 3.1+ 而不是

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多