如何在ActiveAdmin中创建文件下载链接来下载已上传的文件?
我试过这样做:
action_item :only=> :show do
link_to('Download file', [@user, :upload_file])
end
action_item
将在任务栏中建立按钮,但它不会创建实际的路由或控制器的操作方法。
您可以通过在user.rb
中创建自定义member_action来实现下载功能
# In app/admin/users.rb
action_item only: [:show] do
link_to('Download File', download_admin_user_path(resource)) if resource.upload_file.present?
end
member_action :download, method: :get do
user = User.find(params[:id])
send_file user.upload_file
end
或者,我的偏好,只是利用upload_file.rb
# In app/admin/users.rb
action_item only: [:show] do
# NOTE: remove period from file extension
file_ext = resource.upload_file.file_extension.gsub('.', '')
link_to('Download File', download_admin_upload_file_path(resource.upload_file, format: file_ext)) if resource.upload_file.present?
end
# In app/admin/upload_files.rb
controller do
def show
if params[:format] == 'txt' # example of a known mimetype, e.g. text file
send_data resource.path, type: 'text/plain'
elsif params[:format] == resource.file_extension # example of unknown mimetype
send_file resource.path
# let ActiveAdmin perform default behavior
else
super
end
end
end
引用:http://activeadmin.info/docs/8-custom-actions.html
我不知道你正在使用的完整代码,但应该可以工作-
路线。rb -
resources :users do
collection do
get :upload_file
end
end
控制器-
def upload_file
send_file @user.upload_file.path, :type => 'application/pdf', :filename => @user.permalink
end
View -
<%= link_to 'Download file', upload_file_users_path(@user) %>