Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please help me send a jpg file using send_data

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.

like image 791
user206481 Avatar asked Nov 08 '09 23:11

user206481


1 Answers

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
like image 100
Matt Haley Avatar answered Sep 30 '22 03:09

Matt Haley