我有一个Redmine插件。我在 /tmp 中创建一个临时文件,然后使用 File.open 发送它。我想在用户下载临时文件后删除它。我能怎么做 ?
我的代码(在控制器中):
File.open(filelocation, 'r') do |file|
send_file file, :filename => filename, :type => "application/pdf", :disposition => "attachment"
end
如果我在 File.open 之后删除该文件,它将不起作用。
EDIT
在我的控制器中我这样做:
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。
我使用 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 方法之后从服务器删除文件 https://stackoverflow.com/questions/18232088/in-ruby-on-rails-after-send-file-method-delete-the-file-from-server
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)