Ruby-on-rails 如何从rails应用程序下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6392003/
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-03 01:25:18  来源:igfitidea点击:

How to download a file from rails application

ruby-on-railsviewdownload

提问by bdeonovic

I can't seem to find a simple and clear answer to this problem anywhere! Everything seems either outdated or incomplete!

我似乎无法在任何地方找到这个问题的简单而明确的答案!一切似乎都已过时或不完整!

I just want the user to be able to click on a link or button and download a file (that is somewhere in the public folder)

我只希望用户能够单击链接或按钮并下载文件(位于公共文件夹中的某处)

I tried this:

我试过这个:

#view
<%= link_to "Raw blast output" ,:action => :download, :file_name => "public/data/02_blastout/#{@bl_file}" %>
#controller
def download
    send_file "#{RAILS_ROOT}/#{params[:file_name]}"
end

but I get this error:

但我收到此错误:

No route matches {:action=>"download", :file_name=>"public/data/02_blastout/input0.fa_x_Glyma1aaunq.bl", :controller=>"cvits"}

Thanks for the help!!

谢谢您的帮助!!

回答by Mario

Don't use send_filewith a parameter set by a user. This opens up a massive security hole, allowing a user to access any file that is readable by your application (namely, your entire application, but also possibly other files on the filesystem).

不要send_file与用户设置的参数一起使用。这打开了一个巨大的安全漏洞,允许用户访问您的应用程序可读的任何文件(即您的整个应用程序,但也可能是文件系统上的其他文件)。

Rather, if the file is under public, link to the file itself. In your case:

相反,如果文件是公开的,则链接到文件本身。在你的情况下:

<%= link_to "Raw blast output", "/data/02_blastout/#{@bl_file}" %>

No need for a special controller action.

不需要特殊的控制器操作。