Rails3从公共目录下载excel

时间:2017-08-01 08:04:02

标签: ruby-on-rails-3

您好我正在尝试在我的项目中创建一个图标,点击它应该从公共目录下载文件。

我没有收到任何错误,但仍然没有下载

请指出我缺少的东西。提前致谢

html.erb

<%= image_tag('down.png', :alt => 'Download file',  :title => 'Download file', :id => 'download_sample_icon') %>

<% content_for (:jq) do %>
    fetch_file_name = function(){
    $.ajax({
      url : "/file_uploads/download_import_sample",
      data : { file_name: $('#file_upload_action').val() }
    });
  }
  $(document).on("click", "#download_sample_icon", fetch_file_name);

file_uploads_controller.rb

def download_import_sample
  file_name = params[:file_name] && params[:file_name].split(' ').map{|e| e.downcase}.join('_')+".xlsx"
  send_file "#{Rails.root}/public/import_samples/"+"#{file_name}" if file_name.present?
end

控制台输出

Started GET "/file_uploads/download_import_sample?file_name=file+one" for 127.0.0.1 at 2017-08-01 13:22:22 +0530 (pid:2840)
Processing by FileUploadsController#download_import_sample as */* (pid:2840)
Parameters: {"file_name"=>"file one"} (pid:2840)
User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 3446 LIMIT 1 (pid:2840)
Company Load (0.2ms)  SELECT `companies`.* FROM `companies` WHERE `companies`.`id` = 1060 LIMIT 1 (pid:2840)
Sent file /home/user/Project/base/public/import_samples/file_one.xlsx (0.1ms) (pid:2840)
Completed 200 OK in 120ms (pid:2840)

1 个答案:

答案 0 :(得分:0)

尝试

def download_import_sample
  excel_file = File.join(Rails.root, "public", "folder_in_public_directory")
  fileName = params[:file_name] && params[:file_name].split(' ').map{|e| e.downcase}.join('_')+".xlsx"
  send_file(File.join(excel_file, fileName))
end