在Ruby on Rails中,在send_file方法之后,从服务器删除文件 [英] In Ruby on Rails, After send_file method delete the file from server

查看:96
本文介绍了在Ruby on Rails中,在send_file方法之后,从服务器删除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码在Rails中发送文件.

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.

Rails中有任何方法,一旦send_file操作完成,就从服务器中删除文件.

So is there any way in Rails, once the send_file operation is completed delete the file from server.

对此将提供任何帮助.

谢谢,
赤丹

Thanks,
Chetan

推荐答案

由于使用的是send_file,Rails会将请求传递到HTTP服务器(nginx,apache等)-

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.

您可以尝试使用send_data,它将阻塞直到发送数据为止,从而允许您的File.delete请求成功.请记住,尽管send_data需要数据流作为其参数,而不是路径,所以您需要先打开文件:

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.

这篇关于在Ruby on Rails中,在send_file方法之后,从服务器删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆