【问题标题】:Serving non-public binary files from a Rack application从 Rack 应用程序提供非公共二进制文件
【发布时间】:2012-10-31 07:13:08
【问题描述】:

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

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

示例响应:

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

我查看了Rack::Sendfile,但据我了解,它是一个中间件,无法从应用程序本身内部发送文件。

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

【问题讨论】:

    标签: ruby rack


    【解决方案1】:

    机架响应主体必须响应#each{|d|}。所以你可以像这样流式传输响应:

    class FileStreamer
      def initialize(path)
        @file = File.open(path)
      end
    
      def each(&blk)
        @file.each(&blk)
      ensure
        @file.close
      end
    end
    

    用法:

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

    【讨论】:

    • 谢谢,是否需要在 config.ru 中添加“use Rack::Chunked”才能发挥最佳效果?
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 2015-03-29
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 2011-05-07
      • 2023-04-01
      • 2020-11-18
      相关资源
      最近更新 更多