2010-05-10 100 views
11

我有一個簡單的sinatra應用程序需要生成一個文件(通過外部進程),將該文件發送到瀏覽器,最後從文件系統中刪除該文件。沿着這些路線的東西:但是如何在通過send_file發送Sinatra文件後刪除文件?

class MyApp < Sinatra::Base 
    get '/generate-file' do 

    # calls out to an external process, 
    # and returns the path to the generated file 
    file_path = generate_the_file() 

    # send the file to the browser 
    send_file(file_path) 

    # remove the generated file, so we don't 
    # completely fill up the filesystem. 
    File.delete(file_path) 

    # File.delete is never called. 

    end 
end 

看來,該send_file呼叫完成請求,並在其後的任何代碼沒有得到運行。

有什麼方法可以確保生成的文件在成功發送到瀏覽器後進行清理?或者我需要在某個時間間隔內使用運行清理腳本的cron作業?

回答

3

不幸的是,使用send_file時沒有任何回調。這裏常見的解決方案是使用cron任務清理臨時文件

0

這可能是對文件的內容臨時存儲在一個變量的解決方案,如:

內容= file.read

在此之後,刪除文件:

File.delete(FILE_PATH)

最後,返回的內容:

內容

這與你的send_file()同樣的效果。

+0

這不會使用更多的內存嗎? – James 2012-06-21 18:24:04

+0

-1,如果該文件長度爲4GB,該怎麼辦? – yeyo 2014-10-27 03:39:12

+0

@Kira,發送一個4GB的文件到瀏覽器? 'generate_the_file()'方法應該阻止這種情況。我的建議是更改操作順序,以便在瀏覽器接收文件之前刪除生成的文件...原始問題。 – 2014-11-03 18:16:13

相關問題