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.rb213 chars12 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.rb682 chars29 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.rb68 chars2 lines
gistlibby LogSnag