send_file / send_data不发送文件进行下载

时间:2016-10-19 13:31:48

标签: ruby-on-rails ruby ruby-on-rails-3.2

我使用rails 3.2.22.4和ruby 2.2.4。我正在测试send_file功能。我得到"文件发送"在服务器日志中,但我不能看到它在浏览器中下载。单击“保存”按钮将调用此操作。

def save_trunk_logs
  device_id = params['device_id']
  trunk_name = params['trunk_name'] ||= "test"
  data =""
  file = "#{trunk_name}.txt"
  trunk_logs = TrunkStatusLog.select([:LogType, :LogMessage, :EpochLoggedAtTime]).where(DeviceID: device_id)
  File.open(file, "w+") do |aFile|
    aFile.write("Trunk Name : #{trunk_name}\n")
    aFile.write("*"*100)
    aFile.write("\n")
    aFile.write("Time Stamp"+"\t"+"Log Message\n")
    trunk_logs.each do |msg|
      data =format_log_messages msg
      aFile.write("#{data}\n")
    end
  end
  send_file file, :type => 'text/plain; charset=UTF-8', :disposition => 'attachment'
end

此操作由button_to点击事件调用。

$("input[value='Download']").on('click', function () {
    $.ajax({
        type: "POST",
        url: "/dm/trunk_test_tools/save_trunk_logs?device_id="+selectedTrunkDeviceId+"&trunk_name="+selectedTrunkDeviceName,
       }
    })
});

每次我点击下载按钮2都会进行通话。服务器端日志粘贴在

下面
Started POST "/X/Y/save_trunk_logs?device_id=9&trunk_name=SIP_1" for      10.198.2.208 at 2016-10-24 12:58:58 +0530
Processing by ABCController#save_trunk_logs as */*
Parameters: {"device_id"=>"9", "trunk_name"=>"SIP_1"}
Sent file SIP_1.txt (0.0ms)
Completed 200 OK in 98.0ms (ActiveRecord: 62.0ms)

Started POST "/X/Y/save_trunk_logs" for 10.198.2.208 at 2016-10-24 12:58:59 +0530
Processing by TrunkTestToolsController#save_trunk_logs as HTML
Parameters: {"authenticity_token"=>"3HSxduOUwccwo="}
sent file test.txt (0.0ms)
Completed 200 OK in 17.0ms (ActiveRecord: 3.0ms)

我不明白为什么要进行第二次通话以及从何处进行通话。在第一个服务器调用它说文件已发送但不下载。在第二个调用文件中发送以及下载。但它没用。参数不正确。我不是作为参数发送的真实性令牌。(跳过实际的数据查询。)

任何帮助将不胜感激。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我不知道为什么这种方法有效。但是符合我的目的。

$("#btn_id").on('click', function () {
    window.location = ypur api url;
});

谢谢,

阿吉特