当 send_file 结束时清理/tmp [英] clean /tmp when send_file is over
问题描述
我有一个 Redmine 插件.我在/tmp 中创建了一个临时文件,然后用 File.open 发送它.我想在用户下载临时文件时删除它.我该怎么办?
I have a Redmine plugin. I create a temporary file in /tmp, then I send it with File.open. I want to delete the temporary file when user has download it. How can I do ?
我的代码(在控制器中):
My code (in a controller):
File.open(filelocation, 'r') do |file|
send_file file, :filename => filename, :type => "application/pdf", :disposition => "attachment"
end
如果我在 File.open 之后删除文件,它不起作用.
If I remove the file after File.open, it doesn't work.
编辑
在我的控制器中:
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.
My temporary file is remove, but not in the end of my code: the File.open return a damage PDF.
推荐答案
我使用 send_data 而不是 send_file,然后我删除了文件.send_data 将阻塞直到数据发送,允许 File.delete 请求成功.
I use send_data instead of send_file, then I delete the file. send_data will block until the data is sent, allowing File.delete request to succeed.
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)
来源:在Ruby on Rails,在 send_file 方法后从服务器中删除文件
这篇关于当 send_file 结束时清理/tmp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!