# Send\_file with temporary files -- how to delete file after sending?

**URL:** <https://www.ruby-forum.com/t/send-file-with-temporary-files-how-to-delete-file-after-sending/193634>\
**Category:** Rails\
**Created:** [August 20, 2010, 9:41pm UTC](https://www.ruby-forum.com/t/send-file-with-temporary-files-how-to-delete-file-after-sending/193634 "2010-08-20T21:41:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![wickie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/ba9def/32.png) [@wickie](https://www.ruby-forum.com/u/wickie)\
**Post date:** [August 20, 2010, 9:41pm UTC](https://www.ruby-forum.com/t/send-file-with-temporary-files-how-to-delete-file-after-sending/193634/1 "2010-08-20T21:41:54Z")

</div>

I’m looking for a way to stream temporary files and make sure they are  
deleted after they are sent.

With Mongrel I can do something like this

Tempfile.open(‘ue-basket-’) do |zip|  
Zip::ZipOutputStream.open(zip.path) do |zos|  
items.each do |item|  
zos.put\_next\_entry(item.filename)  
zos.write(item.data)  
end  
end

```
send_file zip.path, :type => 'application/zip',
 :filename => item.filename

zip.unlink

```

end

By Unix filesystem semantics, zip.unlink does not free the blocks  
(inodes) that make up the file. As long as there still is a reference to  
it, the file still exists. However, the directory entry for the file is  
deleted. The nice effect is that the file is no longer visible, but can  
still be streamed. As soon as the last file descriptor referencing it is  
closed, the file is finally deleted for good.

This doesn’t work anymore, when serving files is offloaded to the web-  
server. The default Rails 3 (Rack-)middleware detects that a file is  
being send (respond\_to?(:to\_path)), adds the file’s path as a special  
header, which in turn is interpreted by the web server to serve that  
particular file. Of course this can only work if the file is still  
visible in the filesystem. Therefore the unlink trick doesn’t apply.

As a last resort, I can set up a cron job that removes temporary files  
after they’ve reached a certain age. I’m still hoping for a more elegant  
solution. Say, a hook that is executed after the server has finished  
sending the file.

I’m using apache 2.2 and mod\_xsendfile 0.9.

Michael

–  
Michael S.  
[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
[http://www.schuerig.de/michael/](http://www.schuerig.de/michael/)
