不在机架应用程序中加载图像

时间:2014-10-03 06:28:59

标签: rack

我创建了一个简单的机架应用程序来显示指定的目录内容。但问题是如果目录有任何img文件,我希望它以小缩略图显示。

"

require 'rubygems'
require 'rack'
require 'rack/server'

class EnvInspector
    def self.call(env)
            request = Rack::Request.new env
        @name=request.params["path"]
        @name.prepend("/home/")
        @result="";
         if File::directory?((@name.to_s))
              Dir.foreach(@name) do |item|
                    item=item.sub(/([^\s]+(\.(?i)(jpg|png|gif|bmp))$)/,"<img src=\"#{@name}\/\\0\" width=100px height=100px/>")
                @result =@result + "<li>#{item}</li>"
                  end
                  @result.prepend("<ul>");
            @result+="</ul>";
            [200, {"Content-Type"=>"text/html"},["#@result"]]


                     else
                         [200, {"Content-Type"=>"text/html"},["No file in this directory"]]

        end


        end
end

Rack::Server.start :app => EnvInspector "

它没有在浏览器中显示图像。甚至浏览器也能获得正确的img路径。

1 个答案:

答案 0 :(得分:1)

通过提供图片网址的相对路径解决了这个问题

require 'rubygems'
require 'rack'
require 'base64'
require 'rack/server'
require 'nokogiri'         

class EnvInspector
    def self.call(env)
        request = Rack::Request.new env
        @name=request.params["path"]
        @name.prepend("/home/")
        @result="";

         if File::directory?((@name.to_s))
              Dir.foreach(@name) do |item|
              fname = item
                      if fname.match(/([^\s]+(\.(?i)(jpg|png|gif|bmp))$)/)
                              file = File.open("#{@name}/#{item}")
                              data = file.read
                            img_encoded = Base64.encode64(data)
                              items = "<img src='data:image/*;base64, #{img_encoded}' width= 100px height=100px/>"
                            @result =@result + "<li  class=\"list-group-item\">#{items}</li>"

                    else
                         @result=@result + "<li>#{item}</li>"
                    end
              end
                          @result.prepend("<ul>");
                            @result+="</ul>";
                            [200, {"Content-Type"=>"text/html"},["#@result"]]


       else

                    [200, {"Content-Type"=>"text/html"},["No file in this directory"]]

         end            
  end
end

Rack::Server.start :app => EnvInspector