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

后端 未结 3 770
执笔经年
执笔经年 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 02:52

    If you are generating on the fly the file you are trying to send, a solution is to use the Tempfile class:

    begin
      # The second argument is optional:
      temp_file = Tempfile.new(filename, temp_directory)
    
      # ... edit temp_file as needed.
    
      # By default, temp files are 0600,
      # so this line might be needed depending on your configuration:
      temp_file.chmod(0644)
      send_file temp_file
    ensure
      temp_file.close
    end
    

    Contrary to what is indicated in this question, this works as expected (the file stays on the server long enough to be served, but ultimately gets deleted); this post seems to indicate this is due to updates in Rails 3.2.11, something I couldn’t verify.

提交回复
热议问题