create a http server and upload a file in ruby

To create an HTTP server in Ruby, you can use the built-in WEBrick library. Here's an example code to create a simple HTTP server that listens on port 8000:

main.rb
require 'webrick'

server = WEBrick::HTTPServer.new(Port: 8000)

trap('INT') { server.shutdown }
server.mount_proc '/' do |req, res|
  res.content_type = 'text/plain'
  res.body = 'Hello World!'
end

server.start
213 chars
12 lines

Now that we have an HTTP server running, let's see how to receive file uploads from clients. For this, we need to create an endpoint that handles POST requests with file data in the body. Ruby provides a built-in Rack library that simplifies handling HTTP requests.

main.rb
require 'webrick'
require 'rack'

server = WEBrick::HTTPServer.new(Port: 8000)

trap('INT') { server.shutdown }
server.mount_proc '/upload' do |req, res|
  if req.request_method == 'POST'
    env = req.to_rack_env
    uploader = Rack::Multipart.new(env).params['file']
    if uploader
      filename = uploader[:filename]
      File.open(filename, 'wb') do |file|
        file.write(uploader[:tempfile].read)
      end
      res.status = 200
      res.body = "The file #{filename} has been uploaded successfully!"
    else
      res.status = 400
      res.body = 'File upload failed!'
    end
  else
    res.status = 405
    res.body = 'Method not allowed!'
  end
end

server.start
682 chars
29 lines

In this code, we have mounted an endpoint at /upload to receive POST requests. The Rack::Multipart class helps in parsing the HTTP request body and extracting the uploaded file data. We write the uploaded file to disk with the File class and return a success message to the client.

You can test this code by sending a POST request with a file attached to the /upload endpoint. For example, using curl:

main.rb
$ curl -X POST -F file=@path/to/myfile http://localhost:8000/upload
68 chars
2 lines

gistlibby LogSnag