I am using following code for sending the file in Rails.
if File.exist?(file_path) send_file(file_path, type: 'text/excel') File.delete(file_path) end
In this I am trying to send the file and delete the file from server once it is been send successfully. But I am facing issue is, the delete operation is getting executed while sending is performing and due to that I don't see anything in browser.
So is there any way in Rails, once the send_file operation is completed delete the file from server.
Any help on this would be highly appreciated.
Thanks,
Chetan
Because you're using
send_file, Rails will pass the request along to your HTTP server (nginx, apache, etc. - See the Rails documentation on send_file regarding X-Sendfile headers). Because of this, when you try to delete the file, Rails doesn't know that it's still being used.You can try using
send_datainstead, which will block until the data is sent, allowing yourFile.deleterequest to succeed. Keep in mind thatsend_datarequires a data stream as its argument though, not a path, so you need to open the file first:The other option would be a background job that periodically checks for temp files to delete.