Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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 symbolic link because this app is actually deployed through Tomcat, and Tomcat tries to follow the symbolic link and delete all the images in the mount when I shut down Tomcat. Putting the images under public/images is also not an option due to the number and size of these files.

I looked into send_file, but that will just display the one image. I need to display 6 requested images in a nicely formatted page. I would prefer not to use Base64 encoding because of the bloat, but I don't know how else to pass the image data down with the rendered page.

Again, the issue is that the images cannot be accessed via url in the generated HTML, the image data must be passed down with the rest of the page. I know that creating some type of service to server up the images would be the best way to handle this, but right now I just need to get this working.

Any help greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

<img src="/serve_image/image1.jpg">
<img src="/serve_image/image2.jpg">
<img src="/serve_image/image3.jpg">
<img src="/serve_image/image4.jpg">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...