Ruby/Webrick File upload using multipart/form-data

Sunday, January 25, 2009

One of the challenges I'm running into with Ruby is that there isn't the same level of reference documentation as there is in Java. It took me far too long to work out how to implement HTTP multipart file upload in Ruby so I'm posting the code here in the hope that it is useful for others.

The following Ruby source is for a web server with a file upload servlet that accepts multpart/form-data file uploads.

#!/usr/local/bin/ruby
require 'webrick'
require 'stringio'
include WEBrick

s = HTTPServer.new( :Port => 8090 )

class FileUploadServlet < HTTPServlet::AbstractServlet
def do_POST(req, res)
filedata= req.query["filename"]

f = File.open("foo.out", "wb")
f.syswrite req.filedata
f.close

puts "Saved file OK"
end
end
s.mount("/upload", FileUploadServlet)

trap("INT"){ s.shutdown }
s.start


This is the HTML form to test this servlet with


<form action="http://localhost:8090/upload" method="POST" enctype="multipart/form-data">
File: <input type="file" name="filename"><br/>
<input type="submit" value="Upload">
</form>

Labels: