views:

219

answers:

2

I'm using the following tags in my html.erb to both display and download a jpg file that is not in the public/images folder:

<%= image_tag retrieve_photo_path(@photo) %>
<%= link_to "Download Photo", download_photo_path(@photo) %>

my controller code looks like:

def retrieve
  @photo = Photo.find(params[:id])
  send_data File.read(@photo.abs_filepath), :type = "image/jpeg", :disposition => "inline"
end

def download
  @photo = Photo.find(params[:id])
  send_file @photo.abs_filepath, :type = "image/jpeg", :filename => @photo.filename
end

The download link works perfectly, but the image tag displays a red x (broken image). What am I missing? I'm using InstantRails on WinXP, updated to Rails 2.3.4 and Ruby 1.8.6.

A: 

Since your image isn't in the public/images folder, it's most likely not visible via http, that's why you get the red x.

Jeff Paquette
I know the jpg isn't directly visible via http like the other site graphics, that's why I've written a controller method to serve it up. It's a photo I only want accessible for logged in users (I didn't show the authentication code)
A: 

You're not reading the file data properly, you need to open the file first.

Modify your retrieve action as follows:

def retrieve
  @photo = Photo.find(params[:id])
  File.open(@photo.abs_filepath, 'rb') do |f|
    send_data f.read, :type => "image/jpeg", :disposition => "inline"
  end
end
Matt Haley
hallelujah! that was it! Interesting that I didn't get an error message.
thank you very much!