Hi,

In message <4050cf76$0$29350$3b214f66 / aconews.univie.ac.at>,
 `Martin Pirker <nospam / tugraz.at>' wrote:
> Is there somewhere some example code for handling a file upload via
> webrick, meaning a simple form with a (local) file selector, then doing
> a POST(?) operation and webrick receives and dumps the file somewhere.

How about the attached sample?

> As a must requirement, there must be a way to restrict upload size
> (e.g. 100kb) to stop malicious users.

Request body is not read from socket when servlets are
started. If the value of content-length is too large, we can
pass the process of servlets by raising an exception. But
HTTPServer is going to read the body before sending response;-)

Is it better that there is a way to shutdown the socket
without reading request?

-- 
gotoyuzo


require "webrick"

class PostSampleServlet < WEBrick::HTTPServlet::AbstractServlet
  def initialize(server, limit)
    @max_content_length = limit
    super
  end

  def do_GET(req, res)
    content_length = req['content-length'].to_i
    if content_length > @max_content_length
      raise WEBrick::HTTPStatus::BadRequest, "body is too large"
    end
    if data = req.query["data"]
      filename = data.filename
    end
    res.body =<<-_end_of_html_
<html>
 <form method="POST" enctype="multipart/form-data">
  <input type="file" name="data" /><input type="submit" /></form>
 filename = #{WEBrick::HTMLUtils.escape(filename.inspect)}
 <pre>#{WEBrick::HTMLUtils.escape(data)}</pre>
</html>
    _end_of_html_
    res["content-type"] = "text/html"
  end

  def do_POST(req, res)
    do_GET(req, res)
  end
end

svr = WEBrick::HTTPServer.new(:Port=>10080)
svr.mount("/", PostSampleServlet, 100000)
trap(:INT){ svr.shutdown }
svr.start