rails - x-sendfile + 临时文件 [英] rails - x-sendfile + temporary files
问题描述
前段时间我写了一个一个问题 关于在 rails 应用程序中使用临时文件.在特定情况下,我决定使用 tempfile
Some time ago I wrote a question regarding the use of temporary files within a rails app. On thar particular case, I decided to use tempfile
如果我还想使用 x-sendfile
指令(作为 Rails 2 中的参数,或作为 Rails 3 中的配置选项),以便文件发送由我的 Web 服务器直接处理,不是我的 Rails 应用.
This causes a problem if I also want to use the x-sendfile
directive (as a parameter in Rails 2, or as a configuration option in Rails 3) so that the file sending is handled by my web server directly, not my rails app.
所以我想这样做:
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
这个设置有一个问题:文件在发送之前被删除了!
This setup has one issue: the file is deleted before being sent!
一方面,tempfile
会在 Tempfile.open
块结束后立即删除文件.另一方面,x-sendfile
使 send_file 调用异步 - 它返回非常快,因此服务器几乎没有时间发送文件.
On one hand, tempfile
will delete the file as soon as the Tempfile.open
block is over. On the other, x-sendfile
makes the send_file call asynchronous - it returns very quickly, so the server hardly has time to send the file.
我现在最好的解决方案是使用非临时文件(文件而不是临时文件),然后是定期擦除临时文件夹的 cron 任务.这有点不雅,因为:
My best possible solution right now involves using non-temporary files (File instead of Tempfile), and then a cron task that erases the temp folder periodically. This is a bit inelegant since:
- 我必须使用我自己的临时文件命名方案
- 文件在 tmp 文件夹中的停留时间超过了所需时间.
有没有更好的设置?或者,异步 send_file
上是否至少有一个成功"回调,这样我就可以在完成后擦除 f?
Is there a better setup? Or, is there at least a "success" callback on the asynchronous send_file
, so I can erase f when it's done?
非常感谢.
推荐答案
鉴于 Rails3 在可用时使用 x-sendfile,并且没有办法停用它,你只是不能将 send_file 与诸如临时文件.最好的选择是我在问题中提到的那个:使用常规文件,并有一个定期删除旧临时文件的 cron 任务.
Given that Rails3 uses x-sendfile when it is available, and there is no way to deactivate it, you just can't use send_file with a library such as TempFile. The best option is the one I mentioned in the question: use a regular File, and have a cron task that removes old temp files periodically.
删除未使用的文件现在更容易处理女仆宝石:
The removal of unused files has now been easier to deal with with the maid gem:
https://github.com/benjaminoakes/maid
这篇关于rails - x-sendfile + 临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!