Ajith Ajith - 1 year ago 68
Ruby Question

send_file/send_data not sending file for downloading

i'm using rails and ruby 2.2.4. i'm testing send_file feature. I get "file sent" in server logs but i cant see it is getting downloaded in browser. Save button click will call this action.

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("Time Stamp"+"\t"+"Log Message\n")
trunk_logs.each do |msg|
data =format_log_messages msg
send_file file, :type => 'text/plain; charset=UTF-8', :disposition => 'attachment'

This action is called by a button_to click event.

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

every time i hit download button 2 calls are made. server side log is pasted below

Started POST "/X/Y/save_trunk_logs?device_id=9&trunk_name=SIP_1" for 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 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)

I dont understand why second call is made and from where it is being made. in the first server call it says file is sent but does not download. In second call file is sent as well as downloaded. but it is of no use. parameters not not correct. authenticity token i am not sending as parameter.(actual data queries are skipped.)

Any help will be appreciated.
Thanks in advance.

Answer Source

I dont know why this method is working. But serves my purpose.

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



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download