kik*_*ito 8 ruby ruby-on-rails x-sendfile temporary-files
前段时间我写了一个关于在rails应用程序中使用临时文件的问题.在特定情况下,我决定使用tempfile
如果我还想使用该x-sendfile指令(作为Rails 2中的参数,或作为Rails 3中的配置选项),这会导致问题,因此文件发送由我的Web服务器直接处理,而不是我的rails应用程序.
所以我想做这样的事情:
require 'tempfile'
def foo()
# creates a temporary file in tmp/
Tempfile.open('prefix', "#{Rails.root}/tmp") do |f|
f.print('a temp message')
f.flush
send_file(f.path, :x_sendfile => true) # send_file f.path in rails 3
end
end
Run Code Online (Sandbox Code Playgroud)
此设置有一个问题:文件在发送之前被删除!
一方面,tempfile一旦Tempfile.open块结束就会删除文件.另一方面,x-sendfile使send_file调用异步 - 它返回非常快,因此服务器几乎没有时间发送文件.
我现在最好的解决方案是使用非临时文件(File而不是Tempfile),然后是定期擦除temp文件夹的cron任务.这有点不优雅,因为:
有更好的设置吗?或者,异步上至少有一个"成功"回调send_file,所以我可以在完成后删除f吗?
非常感谢.
鉴于 Rails3 在 x-sendfile 可用时使用它,并且无法停用它,因此您不能将 send_file 与 TempFile 等库一起使用。最好的选择是我在问题中提到的一个:使用常规文件,并有一个定期删除旧临时文件的 cron 任务。
编辑:使用女仆宝石现在可以更轻松地处理未使用的文件的删除:
https://github.com/benjaminoakes/maid
| 归档时间: |
|
| 查看次数: |
4795 次 |
| 最近记录: |