Reputation: 11
I have a file server which has to be deleted after a user downloads it. I send the file with send_file
, but I can't just put a File.delete(path)
after that line because send_file returns immediatly, so the file is deleted even before the user receives the complete file.
How do I fix this? I think it's a common problem but haven't found a solution yet.
Here is my code below:
def export_rawdata
@device = Device.find_by_id( params[:id] )
@messages = @device.devmessages.all( :order => "id", :conditions => ["packettime >= ? and packettime <= ?", params[:start_time], params[:end_time]] )
raw_data_path = "#{Rails.root}/tmp/exports/#{@device.s_dev_name}.csv"
FasterCSV.open(raw_data_path, "w+") do |csv|
csv << ["Packet","Created At"]
@messages.each_with_index do |m,i|
x = m.created_at
csv << [m.message, x.strftime('%h %d, %G %r')]
end
end
send_file raw_data_path, :type => "text/csv", :x_sendfile => true, :streaming => false
end
Can Anyone please suggest me, how to delete a file from the server once the download is completed in the client side?
Upvotes: 1
Views: 1988
Reputation: 15525
I have read (once more) the section in the "Rails Guides for Controller, Section sending files". You have chosen the options so your method returns immediately, so there is no chance to get the information that the download has completed. Depending on the network and the client behavior, you will never know if the file download was completed.
So you could think about a workaround (no real code, only the idea):
x * delta minutes
) and delete the whole folder.By that technique, depending on the usage, you will have a constant overhead for older temporary files.
Upvotes: 1