3

如何在 ActiveAdmin 中创建文件下载链接以下载上传的文件?

我试过这样的事情:

action_item :only=> :show do
 link_to('Download file', [@user, :upload_file])
end
4

2 回答 2

6

action_item在任务栏中建立按钮,但不会创建实际路由或控制器的操作方法。

您可以通过在中创建自定义 member_action 来实现下载功能user.rb

# 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

或者,我的偏好,只是利用 RESTful show 动作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

于 2014-10-29T03:01:51.407 回答
1

我不知道您正在使用的完整代码,但这应该可以工作 -

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

查看-

 <%= link_to 'Download file', upload_file_users_path(@user) %>
于 2013-01-16T08:10:59.713 回答