R0b*_*bur 1 ruby-on-rails download
我目前正在使用 RoR 4.1.1 开发自己的应用程序。
我的目标是创建一个存储 .zip 文件的平台,并且希望用户能够下载这些文件。问题是我的老板希望我将文件直接存储到数据库中,而不是存储到文件系统中。
因此我在 ItemsController 中这样做了:
def create
@item = Item.new(item_params)
@item.file = params[:item][:file].read
if @item.save
redirect_to @item
else
render 'new'
end
end
Run Code Online (Sandbox Code Playgroud)
这在我的 new.html.erb 视图中:
<%= f.label :application %>
<%= f.file_field :file %>
<p>
<%= f.submit %>
</p>
Run Code Online (Sandbox Code Playgroud)
这应该使我能够将东西上传到我的数据库。
现在我的数据库中有一个文件列,其中包含二进制文件。但我怎样才能下载这些呢?
您可以使用控制器方法启动下载send_data
。此处的文档:http ://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_data
假设您为下载操作创建了一条路线:
get '/items/:id/download', as: :item_download
Run Code Online (Sandbox Code Playgroud)
并向您的用户提供您的商品的链接:
link_to 'Download', item_download_path(@item), disable_with: 'Downloading...'
Run Code Online (Sandbox Code Playgroud)
现在您的控制器向用户发起下载:
def download
item = Item.find params[:id]
send_data item.file, filename: item.name, type: 'zip', disposition: 'attachment'
end
Run Code Online (Sandbox Code Playgroud)
一旦用户单击该Download
链接,该链接就会变灰并变为 ,Downloading...
然后浏览器将打开其下载对话框并开始下载 zip 文件。
注意:我假设你item
有一个name
方法,但它可以是你想要的任何方法。重要的选项是type: 'zip', disposition: 'attachment'
. 类型是文件类型,可帮助您的浏览器了解它是什么,以及浏览器下载文件或将其呈现在页面上的配置。例如,如果您正在下载 pdf 文件,传递disposition: 'inline'
将使浏览器显示 pdf 而不是直接下载。