5

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.

user206481
  • 248
  • 5
  • 13
  • Check your server logs or output for the request to the "retreive" action. You'll likely find some error messages there that may help you figure it out. – nicholaides Nov 08 '09 at 23:54
  • If I type the url "www.mytestapp.com/photos/3/retrieve" directly into my browser (IE) to simulte the img request, I get the red x broken image -- and my apache access.log has the following entry: "GET /photos/3/retrieve HTTP/1.1" 304 0 can anyone help with what that status code 304 means? – user206481 Nov 09 '09 at 01:03
  • it looks like it has something to do with Apache caching, but I am not familiar with that at all -- please help! – user206481 Nov 09 '09 at 01:18

1 Answers1

10

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
  • 4,304
  • 4
  • 25
  • 17