Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 通过send_file发送文件后,如何删除Sinatra中的文件?_Ruby_Sinatra - Fatal编程技术网

Ruby 通过send_file发送文件后,如何删除Sinatra中的文件?

Ruby 通过send_file发送文件后,如何删除Sinatra中的文件?,ruby,sinatra,Ruby,Sinatra,我有一个简单的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(

我有一个简单的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
classmyapp
然而,
send_file
调用似乎完成了请求,并且之后的任何代码都不会运行


是否有办法确保生成的文件在成功发送到浏览器后被清除?或者我需要求助于在某个时间间隔运行清理脚本的cron作业吗?

不幸的是,使用send\u file时没有任何回调。这里的常见解决方案是使用cron任务来清理临时文件

它可以是一种将文件内容临时存储在变量中的解决方案,如:

contents=file.read

在此之后,删除文件:

File.delete(文件路径)

最后,返回内容:

内容


这与您的
send_file()

send_file正在对文件进行流式处理的效果相同,它不是一个同步调用,因此您可能无法捕获文件的结尾以清理文件。我建议将其用于静态文件或真正大的文件。对于大文件,您需要一个cron作业或其他解决方案,以便稍后进行清理。不能用相同的方法执行,因为当执行仍在get方法中时,send_文件不会终止。如果您并不真正关心流媒体部分,那么可以使用同步选项

begin
   file_path = generate_the_file()  
   result File.read(file_path)
   #...
   result # This is the return
ensure
   File.delete(file_path) # This will be called..
end

当然,如果您对该文件不感兴趣,您可以坚持使用Jochem的答案,该答案完全消除了开始和结束。

这会不会占用更多内存?@Kira,将4GB文件发送到浏览器?在
generate\u the\u file()
方法中应防止出现这种情况。我的建议是更改操作顺序,以便在浏览器收到文件之前删除生成的文件。。。原来的问题。@James,可能是。。。(尽管虚拟机可以智能地使用中间结果的内存)。但它解决了原始请求中的问题…我迟到了10年,但是您可以用ruby编写一个cron任务示例来实现这一点吗?或者使用什么?