Ruby-on-rails 如何使用send_file下载文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22002020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:24:11  来源:igfitidea点击:

How to download file with send_file?

ruby-on-railsruby-on-rails-4sendfile

提问by user3339562

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

有人可以启发我如何下载文件send_file吗?

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

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

For each path it says:

对于每条路径,它说:

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

What could be a problem here? Thanks!

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

回答by Coenwulf

Try:

尝试:

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

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

回答by Mukesh

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

回答by corpico

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.

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

回答by Paritosh Piplewar

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

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

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

回答by Gurudath BN

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'