File uploads
suggest changeBrowsers upload files with a POST request whose body is encoded as multipart/form-data. The body is split into parts separated by a random boundary string; each part has its own headers (field name, original file name, content type) followed by the raw bytes:
POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----XyZ123
Content-Length: 412
------XyZ123
Content-Disposition: form-data; name="title"
Kitty
------XyZ123
Content-Disposition: form-data; name="file"; filename="cat.png"
Content-Type: image/png
<binary PNG bytes>
------XyZ123--
In Ruby you rarely parse this yourself. Rack (the layer under Sinatra, Rails, Hanami and Roda) parses the body, writes each file to a Tempfile and hands your code a small Hash describing it. This article covers the server side (receiving, validating and storing uploads), the client side (sending files from Ruby) and testing.
The HTML form
A form must use method="post" and enctype="multipart/form-data". Without the enctype the browser sends only the file name, not its contents:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="file" accept=".png,.jpg,.jpeg,.pdf">
<button>Upload</button>
</form>
accept only filters the browser's file picker. It is a convenience for users, not a security check: anyone can send any bytes with curl.
Receiving a file in Sinatra
For a file field, params[:file] is a Hash (string and symbol keys both work in Sinatra):
require 'sinatra'
post '/dump' do
content_type :text
params.inspect
end
$ curl -F file=@cat.png -F title=Kitty http://localhost:4567/dump
{"file" => {"filename" => "cat.png", "type" => "image/png", "name" => "file",
"tempfile" => #<Tempfile:/tmp/RackMultipart20261017-645-wefod0.png>,
"head" => "Content-Disposition: form-data; name=\"file\"; filename=\"cat.png\"\r\nContent-Type: image/png\r\n"},
"title" => "Kitty"}
| Key | Meaning |
|---|---|
:tempfile |
a Tempfile with the uploaded bytes, already on disk |
:filename |
file name sent by the client (directories already stripped by Rack) |
:type |
Content-Type sent by the client, e.g. "image/png" |
:name |
form field name |
:head |
raw headers of this part |
Everything except :tempfile comes from the client and can be a lie. Note also that if the client sends a normal text field with the same name (curl -F file=hello), params[:file] is the String "hello", so always check the type before using it.
A complete, safe upload endpoint
A production-ready endpoint should:
- reject requests that are too large, ideally before reading the body
- check that a file was actually sent
- detect the real file type from its first bytes (the "magic number") instead of trusting the extension or
Content-Type - store the file under a name you generate, never the client's name
- keep the original name only as metadata
# app.rb
require 'sinatra'
require 'securerandom'
require 'fileutils'
require 'json'
UPLOAD_DIR = File.expand_path('uploads', __dir__)
MAX_SIZE = 5 * 1024 * 1024 # 5 MB
ALLOWED = { # content type => [extension, magic bytes at start of file]
'image/png' => ['.png', "\x89PNG\r\n\x1A\n".b],
'image/jpeg' => ['.jpg', "\xFF\xD8\xFF".b],
'application/pdf' => ['.pdf', '%PDF-'.b]
}.freeze
FileUtils.mkdir_p(UPLOAD_DIR)
# Cheap early check: refuse bodies that are obviously too big.
# The extra 64 KB allows for multipart headers and other fields.
before do
if request.post? && request.content_length.to_i > MAX_SIZE + 64 * 1024
halt 413, { error: 'upload too large' }.to_json
end
end
helpers do
def detect_type(io)
head = io.read(8).to_s.b
io.rewind
ALLOWED.find { |_type, (_ext, magic)| head.start_with?(magic) }&.first
end
def save_upload(upload)
tempfile = upload[:tempfile]
halt 413, { error: 'file too large' }.to_json if tempfile.size > MAX_SIZE
type = detect_type(tempfile) or
halt 415, { error: 'only PNG, JPEG and PDF allowed' }.to_json
name = "#{SecureRandom.uuid}#{ALLOWED[type][0]}"
File.open(File.join(UPLOAD_DIR, name), 'wb') { |f| IO.copy_stream(tempfile, f) }
{ id: name, original_name: File.basename(upload[:filename].to_s),
type: type, size: tempfile.size }
end
end
post '/upload' do
content_type :json
upload = params[:file]
unless upload.is_a?(Hash) && upload[:tempfile]
halt 400, { error: 'no file uploaded (field "file")' }.to_json
end
info = save_upload(upload)
status 201
info.merge(title: params[:title]).to_json
end
Trying it with curl:
$ curl -F file=@cat.png -F title=Kitty http://localhost:4567/upload
{"id":"a66e251a-a6e8-4284-bb80-99bab5751c49.png","original_name":"cat.png","type":"image/png","size":19,"title":"Kitty"}
$ echo "not an image" > evil.png
$ curl -i -F file=@evil.png http://localhost:4567/upload
HTTP/1.1 415 Unsupported Media Type
...
{"error":"only PNG, JPEG and PDF allowed"}
$ curl -d '' http://localhost:4567/upload
{"error":"no file uploaded (field \"file\")"}
$ head -c 6000000 /dev/zero > big.bin
$ curl -i -F file=@big.bin http://localhost:4567/upload
HTTP/1.1 413 Request Entity Too Large
Why each detail matters:
- Generated names. A client-supplied name can collide with another user's file, contain characters your file system dislikes, or be crafted to overwrite something (
../../config/app.rb). Rack already strips directories fromfilename("../../etc/passwd"arrives as"passwd"), andFile.basenameis a second line of defence, but the safest name is one the client never influences. - Magic bytes, not extensions. An HTML file renamed to
photo.pngwould otherwise be stored and later served from your domain. For many formats, themarcelgem (used by Rails) does this detection for you:Marcel::MimeType.for(io). IO.copy_streamcopies in chunks, so even large files never sit in memory as one String.FileUtils.mv(tempfile.path, dest)is faster when source and destination are on the same file system, but the tempfile is then gone from under Rack, so copying is the simpler default.- Tempfiles are temporary. Rack deletes them after the request (or when they are garbage collected). If you hand the file to a background job, copy it somewhere permanent first.
Multiple files
Name the field with [] and add multiple to the input:
<input type="file" name="photos[]" multiple>
params[:photos] is then an Array of upload hashes. Reusing save_upload from above:
post '/photos' do
content_type :json
uploads = Array(params[:photos]).select { _1.is_a?(Hash) && _1[:tempfile] }
halt 400, { error: 'no files' }.to_json if uploads.empty?
status 201
uploads.map { save_upload(_1) }.to_json
end
$ curl -F 'photos[]=@cat.png' -F 'photos[]=@report.pdf' http://localhost:4567/photos
[{"id":"f64f2983-...png","original_name":"cat.png","type":"image/png","size":19},
{"id":"572bcf4b-...pdf","original_name":"report.pdf","type":"application/pdf","size":14}]
Nested names work too: meta[author]=kjk becomes params[:meta][:author].
Rack limits how much a single request may contain. The defaults are generous and can be tuned with environment variables:
| Variable | Default | Limits |
|---|---|---|
RACK_MULTIPART_FILE_LIMIT |
128 | number of file parts |
RACK_MULTIPART_TOTAL_PART_LIMIT |
4096 | number of parts of any kind |
RACK_MULTIPART_BUFFERED_UPLOAD_BYTESIZE_LIMIT |
16 MB | total size of non-file fields kept in memory |
None of them limits the size of the files themselves; that is the job of your app (as above) and of the front-end web server, e.g. client_max_body_size 5m; in nginx. A limit there rejects huge bodies before Ruby reads a single byte.
Serving uploaded files back
Look files up by your generated id, validate it strictly and send it as an attachment so a browser never renders user content inline on your domain:
get '/files/:id' do
id = params[:id]
halt 404 unless id.match?(/\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\.(png|jpg|pdf)\z/)
path = File.join(UPLOAD_DIR, id)
halt 404 unless File.file?(path)
send_file path, disposition: 'attachment'
end
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Disposition: attachment; filename="572bcf4b-9a86-468a-bde7-10ceda891471.pdf"
Content-Length: 14
X-Content-Type-Options: nosniff
A request such as /files/..%2Fapp.rb fails the regex and gets 404. In a real app you would store original_name in a database and pass it as filename: to send_file so the download keeps its friendly name.
Plain Rack
Without Sinatra, Rack::Request#params returns the same structure, with symbol keys inside the upload hash:
# config.ru
require 'json'
run lambda { |env|
req = Rack::Request.new(env)
upload = req.params['file']
return [400, { 'content-type' => 'text/plain' }, ["missing file\n"]] unless upload.is_a?(Hash)
info = { filename: upload[:filename], type: upload[:type], size: upload[:tempfile].size }
[200, { 'content-type' => 'application/json' }, [info.to_json]]
}
$ rackup -p 4570 config.ru
$ curl -F file=@report.pdf http://localhost:4570/
{"filename":"report.pdf","type":"application/pdf","size":14}
In Rails the upload arrives as an ActionDispatch::Http::UploadedFile (params[:file].original_filename, .content_type, .tempfile, .read), and most apps store it with Active Storage (has_one_attached :avatar), which handles naming, cloud storage (S3, GCS) and content type detection.
Uploading files from Ruby with Net::HTTP
Net::HTTP can build a multipart body with set_form. Each entry is [name, value] or, for a file, [name, io, options]:
require 'net/http'
require 'json'
uri = URI('http://localhost:4567/upload')
req = Net::HTTP::Post.new(uri)
File.open('cat.png', 'rb') do |file|
req.set_form(
[
['title', 'Kitty'],
['file', file, { filename: 'cat.png', content_type: 'image/png' }]
],
'multipart/form-data'
)
res = Net::HTTP.start(uri.host, uri.port, read_timeout: 30) { |http| http.request(req) }
puts res.code
puts JSON.parse(res.body)
end
201
{"id" => "805abf22-291d-442e-93ea-ce677266dfbb.png", "original_name" => "cat.png", "type" => "image/png", "size" => 19, "title" => "Kitty"}
The file is streamed from disk while the request is sent, so this works for large files too. Without the content_type: option the part is sent as application/octet-stream.
Uploading with Faraday
Faraday needs the faraday-multipart gem (gem install faraday-multipart). Wrap each file in a FilePart; an Array value is sent as repeated photos[] parts:
require 'faraday'
require 'faraday/multipart'
conn = Faraday.new(url: 'http://localhost:4567') do |f|
f.request :multipart
f.response :raise_error
end
res = conn.post('/photos', {
photos: [
Faraday::Multipart::FilePart.new('cat.png', 'image/png'),
Faraday::Multipart::FilePart.new('report.pdf', 'application/pdf')
]
})
puts res.status
puts res.body
201
[{"id":"f0cc4bde-...png","original_name":"cat.png","type":"image/png","size":19},{"id":"40c2a1c7-...pdf","original_name":"report.pdf","type":"application/pdf","size":14}]
Don't write the key as 'photos[]' yourself: Faraday adds the brackets for Arrays, and you would end up with photos[][], which the server does not recognise.
Raw uploads without multipart
APIs (and pre-signed S3 URLs) often accept the file as the whole request body, usually with PUT. There is no multipart parsing, so the server can stream the body to disk and stop as soon as it grows too large:
require 'sinatra'
require 'securerandom'
require 'fileutils'
set :port, 4569
MAX_SIZE = 5 * 1024 * 1024
FileUtils.mkdir_p('uploads')
put '/raw/:name' do
path = File.join('uploads', "#{SecureRandom.uuid}#{File.extname(params[:name])}")
written = 0
File.open(path, 'wb') do |f|
while (chunk = request.body.read(64 * 1024))
written += chunk.bytesize
if written > MAX_SIZE
f.close
File.delete(path)
halt 413, 'too large'
end
f.write(chunk)
end
end
status 201
"stored #{written} bytes as #{File.basename(path)}\n"
end
On the client, body_stream sends a file without loading it into memory. You must set Content-Length (or Transfer-Encoding: chunked) yourself:
require 'net/http'
path = 'cat.png'
uri = URI("http://localhost:4569/raw/#{File.basename(path)}")
File.open(path, 'rb') do |file|
req = Net::HTTP::Put.new(uri)
req['Content-Type'] = 'application/octet-stream'
req['Content-Length'] = file.size.to_s
req.body_stream = file
res = Net::HTTP.start(uri.host, uri.port) { |http| http.request(req) }
puts "#{res.code} #{res.body}"
end
201 stored 19 bytes as 69637e49-0946-434d-86b4-260421fd5a1a.png
The curl equivalent is curl -T big.bin http://localhost:4569/raw/big.bin, which here prints too large.
Testing uploads with rack-test
Rack::Test::UploadedFile builds a multipart request without a running server. It accepts a path or any IO, which makes it easy to test invalid content:
# test_upload.rb
ENV['APP_ENV'] = 'test'
require 'minitest/autorun'
require 'rack/test'
require 'json'
require_relative 'app'
class UploadTest < Minitest::Test
include Rack::Test::Methods
def app = Sinatra::Application
def test_accepts_png
file = Rack::Test::UploadedFile.new('cat.png', 'image/png', true) # true = binary
post '/upload', file: file, title: 'Kitty'
assert_equal 201, last_response.status
body = JSON.parse(last_response.body)
assert_equal 'image/png', body['type']
assert_match(/\A\h{8}-.*\.png\z/, body['id'])
end
def test_rejects_fake_png
file = Rack::Test::UploadedFile.new(StringIO.new('not an image'), 'image/png',
original_filename: 'evil.png')
post '/upload', file: file
assert_equal 415, last_response.status
end
def test_requires_file
post '/upload', file: 'just a string'
assert_equal 400, last_response.status
end
end
$ ruby test_upload.rb
...
3 runs, 6 assertions, 0 failures, 0 errors, 0 skips
Checklist
- Limit request size in the web server (nginx, load balancer) and in the app.
- Treat
filenameandtypeas untrusted; detect the type from the content. - Store files under generated names, outside the public web root.
- Serve user files with
Content-Disposition: attachmentandX-Content-Type-Options: nosniff, or from a separate domain / object storage. - Copy the
Tempfilebefore the request ends if processing happens later. - For images, re-encode them (e.g. with
image_processing/ libvips) if you display them; this also strips metadata such as GPS coordinates. - For big files, consider letting browsers upload directly to object storage with pre-signed URLs, so the bytes never pass through your Ruby process.
For calling and building JSON APIs in general see REST APIs; for Content-Type, Content-Disposition and friends see HTTP headers.