Vra

I need a quick tip on something which seems really simple. I have some pictures inside private folder and would like to display them inside my View.

The only solution I found was this:

def show
    send_file 'some/image/url', :disposition => 'inline', :type => 'image/jpg', :x_sendfile => true
end

I've read that :disposition => 'inline' should not trigger image download and allow me to display it inside my View. The problem is that each time I trigger show action, image download is automatically activated and it is automatically downloaded. View for show action is not displayed.

How can I display that image inside my View? Thank you.

Was dit nuttig?

Oplossing

The way I do it, and I'm not saying it's perfectly by the book, is I make a root for images and an action in the controller to render it.

So, for instance, in routes.rb

match '/images/:image', to: "your_controller#showpic", via: "get", as: :renderpic

In your controller:

def showpic
    send_file "some/path/#{params[:image]}.jpg", :disposition => 'inline', 
              :type => 'image/jpg', :x_sendfile => true # .jpg will pass as format
end

def show
end

And in your view

<img src="<%= renderpic_path(your image) %>">

Here is a working example, with fewer parameters on "send_file"

def showpic
    photopath = "images/users/#{params[:image]}.jpg"
    send_file "#{photopath}", :disposition => 'inline'
end

Ander wenke

I think the problem is type. From documentation:

:type - specifies an HTTP content type

So the proper HTTP content type should be image/jpeg instead of image/jpg, as you can see here. Try with:

:type => 'image/jpeg'

You also can list all available types coding Mime::EXTENSION_LOOKUP into a rails console.

Example:

Controller

class ImagesController < ApplicationController
  def show_image
    image_path = File.join(Rails.root, params[:path]) # or similar
    send_file image_path, disposition: 'inline', type: 'image/jpeg', x_sendfile: true
  end
end

Routes

get '/image/:path', to: 'images#show_image', as: :image

Views

image_tag image_path('path_to_image')

You would need to have the view use an image_tag to display on the view.

Similar question was raised here: Showing images with carrierwave in rails 3.1 in a private store folder

Gelisensieer onder: CC-BY-SA met toeskrywing
Nie verbonde aan StackOverflow
scroll top