如何在ActiveAdmin中创建文件下载链接以下载上传的文件?
我试过这样的事情:
action_item :only=> :show do
link_to('Download file', [@user, :upload_file])
end
答案 0 :(得分:4)
action_item
将在任务栏中建立按钮,但它不会创建实际路线或控制器的操作方法。
您可以通过在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
或者,我的偏好,只是利用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
答案 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) %>