Rails 3, displaying jpg images from the local file system above RAILS_ROOT

后端 未结 1 652
陌清茗
陌清茗 2020-12-19 13:12

I\'m trying to figure out a way to display images from a mounted file system that is not under RAILS_ROOT (in RedHat or Ubuntu environments). I don\'t want to use a symboli

1条回答
  •  天涯浪人
    2020-12-19 13:54

    For obvious reasons Rails won't allow a user to access parts of the filesystem outside of RAILS_ROOT/public. You were actually part of the way there when you mentioned sendfile (or x-sendfile for preference.) The solution is to have Rails serve up an html page as normal which contains links to a Rails action which serves up the individual files.

    For example, let's say I want to show some images from somewhere deep in the filesystem. First I have to create an action that serves up one image at a time. So in the config/routes.rb you could add the following:

    match '/serve_image/:filename' => 'images#serve'
    

    Then I have to create a controller to match that route. For example:

    class ImagesController < ApplicationController
      def serve
        path = "/my/servers/image/path/#{params[:filename]}"
    
        send_file( path,
          :disposition => 'inline',
          :type => 'image/jpeg',
          :x_sendfile => true )
      end
    end
    

    Now your images are available under the url: /serve_image/my_image.jpg. So the last thing to do is create a nice html page that shows all the necessary images. It's as simple as:

    
    
    
    
    

    0 讨论(0)
提交回复
热议问题