ActiveAdmin中的文件下载链接

时间:2013-01-16 07:49:24

标签: ruby-on-rails-3 file-upload download activeadmin

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

我试过这样的事情:

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

2 个答案:

答案 0 :(得分:4)

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

中的RESTful show动作
# 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

答案 1 :(得分:1)

我不知道你正在使用的完整代码但是应该有用 -

routes.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) %>