In Ruby on Rails, After send_file method delete the file from server

后端 未结 3 767
执笔经年
执笔经年 2020-12-05 02:16

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
         


        
3条回答
  •  情话喂你
    2020-12-05 03:00

    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_data instead, which will block until the data is sent, allowing your File.delete request to succeed. Keep in mind that send_data requires a data stream as its argument though, not a path, so you need to open the file first:

    File.open(file_path, 'r') do |f|
      send_data f.read, type: "text/excel"
    end
    File.delete(file_path)
    

    The other option would be a background job that periodically checks for temp files to delete.

提交回复
热议问题