如何使用send_file下载文件?

时间:2014-02-25 00:18:31

标签: ruby-on-rails ruby-on-rails-4 sendfile

有人可以告诉我如何使用send_file下载文件?

image.jpg内有app/assets/images个文件。我在我的控制器中试过这个:

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

对于每条路径,它说:

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

这里可能有什么问题?谢谢!

5 个答案:

答案 0 :(得分:9)

尝试:

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

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

答案 1 :(得分: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......

答案 2 :(得分:2)

好吧,我建议你将文件移动到公共文件夹。无论如何,这样做

send_file(Rails.root.join('app' , 'assets', 'images', 'image.jpg'))

答案 3 :(得分:2)

我们需要指定地雷类型,以便它会缓存。

send_file ("#{Rails.root}/public"+image.image_path), :type => "image/jpeg", :disposition => 'inline'

答案 4 :(得分:2)

对于仍在寻找答案的人来说,send_data和send_file在响应ajax调用时不会工作。相反,请尝试提交表单或使用<a href=..>调用控制器方法并下载文件。