4

Can someone enlighten me how can I download file with send_file?

I have a file image.jpg inside app/assets/images. I've tried this in my controller:

def download
    send_file ("#{Rails.root}/public/images/image.jpg")
end

def download
    send_file ("#{Rails.root}/assets/images/image.jpg")
end

def download
    send_file ("#{Rails.root}/images/image.jpg")
end

def download
    send_file ("/public/images/image.jpg")
end

def download
    send_file ("/assets/public/images/image.jpg")
end

def download
    send_file ("/assets/images/image.jpg")
end

For each path it says:

ActionController::MissingFile in HomeController#download
Cannot read file 'some_path'

What could be a problem here? Thanks!

user3339562
  • 1,325
  • 4
  • 18
  • 34

5 Answers5

9

Try:

IMAGES_PATH = File.join(Rails.root, "public", "images")

def download
  send_file(File.join(IMAGES_PATH, "image.jpg"))
end
Coenwulf
  • 1,937
  • 2
  • 15
  • 23
  • Thank you for suggestion but it's the same. Can't find a file. – user3339562 Feb 25 '14 at 00:44
  • You have this error occur even when a image.jpg file exists in the /public/images directory? Maybe try restarting your app server. This should definitely be working. – Coenwulf Feb 25 '14 at 00:54
4
In your view =>
<%= link_to "click here to download", signed_feeds_pdf_path(:feed_image_path => feed_image.feedimage.path), target: '_self' %>

In your controller =>
   def pdf
     file_name = params[:feed_image_path].split('/').last
     @filename ="#{Rails.root}/public/uploads/feed_image/feedimage/#{file_name}"
     send_file(@filename ,
      :type => 'application/pdf/docx/html/htm/doc',
      :disposition => 'attachment')           
  end
soo simple......
Mukesh
  • 921
  • 10
  • 23
3

well, i suggest you to move your file to public folder. Anyway , do this

send_file(Rails.root.join('app' , 'assets', 'images', 'image.jpg'))
Paritosh Piplewar
  • 7,982
  • 5
  • 26
  • 41
3

We need to specify the mine type so that it will cache.

send_file ("#{Rails.root}/public"+image.image_path), :type => "image/jpeg", :disposition => 'inline'
Antzi
  • 12,831
  • 7
  • 48
  • 74
Gurudath BN
  • 1,391
  • 20
  • 21
2

For anyone still looking for an answer, send_data and send_file won't work when responding to ajax calls. Instead, try submitting a form or using <a href=..> to call the controller method and download a file.

corpico
  • 617
  • 3
  • 16
  • 26