send_file结束时清理/ tmp

我有一个Redmine插件。 我在/ tmp中创建一个临时文件,然后用File.open发送它。 我想在用户下载临时文件时删除它。 我能怎么做 ?

我的代码(在控制器中):

File.open(filelocation, 'r') do |file| send_file file, :filename => filename, :type => "application/pdf", :disposition => "attachment" end 

如果我在File.open之后删除该文件,它不起作用。

编辑

在我的控制器中,我做:

 def something temp = Tempfile.new(['PDF_','.pdf']) # ... some code that modify my pdf ... begin File.open(temp.path, 'r') do |file| send_file file, :filename => temp.path, :type => "application/pdf", :disposition => "attachment" end ensure temp.close temp.unlink end end 

我的临时文件已删除,但不在我的代码末尾:File.open返回损坏PDF。

考虑为您的工作使用Tempfile类:

 Tempfile.create('foo', '/tmp') do |f| ... do something with f ... end 

它包含在标准库中,并且在块关闭时自动进行清理。

参考: http : //www.ruby-doc.org/stdlib-2.1.1/libdoc/tempfile/rdoc/index.html

我使用send_data而不是send_file,然后删除文件。 send_data将阻塞,直到发送数据,允许File.delete请求成功。

  file = temp.path File.open(file, 'r') do |f| send_data f.read.force_encoding('BINARY'), :filename => filename, :type => "application/pdf", :disposition => "attachment" end File.delete(file) 

source: 在Ruby on Rails中,在send_file方法之后从服务器中删除该文件