简体   繁体   中英

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

how to display the image, which stored outside from the project directory?

Is there a simple way to do it?

I see two ways :

  • On top of your rails server, in production and sometimes in dev, you have to use a web server like apache or nginx. With these, you can serve files from other directories for specific URL. EG you can make http://yourapp.com/images/ serving files from a specific dir. In rails, display the image with a traditionnal image_tag

Example with 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' %>
  • If you can't access your server settings, you can serve an image file from a controller action with send_file

    In a controller :

     class ImagesController < ApplicationController def show send_file File.join('/var/www/my/specific/folder',params[:name]), :disposition => 'inline' end end 

    In config/routes.rb

     match '/images/:name' => 'images#show', :as => :custom_image 

    Then when you access this action (via the route you defined in config/routes.rb ), you have the image. So in your view you do a traditionnal image_tag with this URL :

     <%= image_tag custom_image_path( 'my_pic.jpg' ) %> OR <%= image_tag custom_image_url( 'my_pic.jpg' ) %> 

If it's stored outside of the Rails app directory, then it does not belong to asset pipeline and you can simply link to it:

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

Obviously it must be accessible through HTTP (you need nginx or Apache server installed).

This is probably bad idea and will lead to a bunch of issues. Some security, some functionality, but most of the effects I actually don't know.
I do know, from experience, that whenever you go against the rails conventions for what and where stuff is, it's a slippery slope of things breaking, best avoided.

Create a solution using the framework provided.

Note this functionality can also be affected a bit if you are using rails 3.1+ as opposed to <= 3.0 due to asset compilation which copies js, css and images into public.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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