Ruby 从机架应用程序提供非公共二进制文件

Ruby 从机架应用程序提供非公共二进制文件,ruby,rack,Ruby,Rack,我正在制作一个简单的机架式应用程序,在身份验证后授予对安全文件的访问权。 由于文件中的数据是敏感的,因此它们位于应用程序的非公用文件夹中 现在,在检查会话数据之后,我只需打开文件进行读取,并将内容作为响应主体发送。 它感觉很难看,对于较大的文件来说,它一定非常消耗资源 答复示例: [ "200", {"Content-Type"=> MIME::Types.type_for(file).first.to_s }, File.open( file ).read() ] 我研究过,但据我所知

我正在制作一个简单的机架式应用程序,在身份验证后授予对安全文件的访问权。
由于文件中的数据是敏感的,因此它们位于应用程序的非公用文件夹中

现在,在检查会话数据之后,我只需打开文件进行读取,并将内容作为响应主体发送。
它感觉很难看,对于较大的文件来说,它一定非常消耗资源

答复示例:

[ "200", {"Content-Type"=> MIME::Types.type_for(file).first.to_s }, File.open( file ).read() ]
我研究过,但据我所知,它是一个中间件,不能从应用程序内部发送文件


从机架应用程序发送非公共二进制文件的最有效方式是什么?

机架响应主体必须响应
#每个{d}
。因此,您可以将响应流式传输如下:

class FileStreamer
  def initialize(path)
    @file = File.open(path)
  end

  def each(&blk)
    @file.each(&blk)
  ensure
    @file.close
  end
end
response = Rack::Response.new
file = open(path_to_binary_file, "rb")
# other stuff…
mime = Mime.mime_type(::File.extname(file.path), 'text/html')
response.headers.merge!( "Content-Type" => mime ) if mime
response.write file
response.finish
用法:

[ "200", {"Content-Type"=> MIME::Types.type_for(file).first.to_s }, FileStreamer.new(file) ]

作为替代方案,如果您使用,您可以执行以下操作:

class FileStreamer
  def initialize(path)
    @file = File.open(path)
  end

  def each(&blk)
    @file.each(&blk)
  ensure
    @file.close
  end
end
response = Rack::Response.new
file = open(path_to_binary_file, "rb")
# other stuff…
mime = Mime.mime_type(::File.extname(file.path), 'text/html')
response.headers.merge!( "Content-Type" => mime ) if mime
response.write file
response.finish

谢谢,这是否需要在config.ru中添加“use Rack::Chunked”才能发挥最佳效果?