How to download file with send_file?

那年仲夏 提交于 2019-12-20 02:11:36

问题


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!


回答1:


Try:

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

def download
  send_file(File.join(IMAGES_PATH, "image.jpg"))
end



回答2:


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......



回答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'))



回答4:


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'



回答5:


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.



来源:https://stackoverflow.com/questions/22002020/how-to-download-file-with-send-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!