skip to content

With Active Storage's direct_upload: true file field, how does the file reach the storage service, and what does the form submit to Rails?

level: middleimportance: should knowfreq 44%

answer

  1. data-direct-upload-url on the input
  2. MD5 checksum computed in the browser
  3. POST /rails/active_storage/direct_uploads
  4. create_before_direct_upload! returns signed_id
  5. hidden field carries the signed id

basics

~20 s

Active Storage's JavaScript intercepts the submit, asks Rails to create a blob record, uploads the bytes straight to the storage service with the returned URL and headers, then submits the form with the blob's signed_id instead of the file.

solid answer

~40 s

`form.file_field :avatar, direct_upload: true` adds `data-direct-upload-url` pointing at `rails_direct_uploads_url`. With the Active Storage JavaScript started (`ActiveStorage.start()`), submitting the form makes it compute a Base64 MD5 checksum of each file, POST the filename, content type, byte size and checksum to `ActiveStorage::DirectUploadsController#create`, which calls `ActiveStorage::Blob.create_before_direct_upload!` and returns the blob's `signed_id` plus an upload URL and headers. The browser PUTs the bytes to that URL, then puts the `signed_id` in a hidden input with the field's name and submits. The controller receives a string, and `attach` or assignment resolves it with `find_signed!`. App servers never stream the file, and the upload survives a failed validation; the costs are orphaned blobs, a public endpoint by default, and checks that run only after the bytes are stored.

code

erb · 7 lines
erb
<%= form_with model: @freelancer do |form| %>
  <% if @freelancer.avatar.attached? %>
    <%= form.hidden_field :avatar, value: @freelancer.avatar.signed_id %>
  <% end %>
  <%= form.file_field :avatar, direct_upload: true, accept: "image/png,image/jpeg,image/webp" %>
  <%= form.submit %>
<% end %>

go deeper

for a junior

Recall that direct_upload: true on a file field plus the Active Storage JavaScript uploads the file straight to storage and the form then submits a signed id.

for a middle

Walk through the sequence: checksum, POST to DirectUploadsController, create_before_direct_upload!, PUT to the service URL, hidden signed_id field, and the events you can hook for progress.

for a senior

Cover what you must add in production: authentication on the blob endpoint, bucket CORS, a scheduled unattached-blob sweep, and validations that clean up rejected files.

for a principal

Decide when direct uploads earn their operational cost versus ordinary form uploads, given file sizes, client networks and how much web-worker time uploads consume.

## The problem direct uploads solve In a plain multipart form, the file travels browser to Rails to storage service: an app server process spends the whole upload streaming bytes, and the file is pushed to the service only after the record saves. For large portfolio videos or a slow mobile connection that ties up a web worker. A **direct upload** sends the bytes from the browser to the storage service, and Rails only handles small JSON requests and the final form. ## Wiring it up 1. Load Active Storage's JavaScript. With import maps, pin `@rails/activestorage` to `activestorage.esm.js` and call `ActiveStorage.start()`; `javascript_include_tag "activestorage"` loads a build that starts itself. 2. Mark the input: `form.file_field :avatar, direct_upload: true`. The option is turned into a `data-direct-upload-url` attribute whose value is `rails_direct_uploads_url` (`/rails/active_storage/direct_uploads`). A plain `<input type="file" data-direct-upload-url="...">` works the same way. 3. For S3 or GCS, allow the app's origin to `PUT` to the bucket in the bucket's CORS rules; the Disk service is served by Rails itself. ## The sequence on submit 1. The script catches the form's submit and dispatches `direct-uploads:start` on the form. 2. For each file it computes an **MD5 checksum** in chunks in the browser (`direct-upload:initialize`, `direct-upload:start`). 3. It POSTs `{ blob: { filename, content_type, byte_size, checksum } }` as JSON, with the page's CSRF token, to **`ActiveStorage::DirectUploadsController#create`** (`direct-upload:before-blob-request`). 4. The controller calls **`ActiveStorage::Blob.create_before_direct_upload!`**, which saves a blob row pointing at a key where no file exists yet, and answers with the blob's attributes, its `signed_id`, and a `direct_upload` object holding a URL and headers. The URL is valid for `service_urls_expire_in`, five minutes by default; on S3 it is signed for the declared content length and MD5. 5. The browser uploads the bytes to that URL (`direct-upload:before-storage-request`, `direct-upload:progress`). 6. It appends a hidden input with the file field's name and the `signed_id` as its value, disables the file input, and resubmits the form (`direct-upload:end`, `direct-uploads:end`). A failure fires `direct-upload:error`, which shows an `alert` unless the event is cancelled. On the server, `params[:freelancer][:avatar]` is now a **string**. Assigning it, or passing it to `attach`, looks the blob up with `ActiveStorage::Blob.find_signed!`, identifies its content type from the first bytes in storage, and creates only the attachment row; nothing is uploaded again. ## What you gain and what you take on | Concern | Form upload through Rails | Direct upload | |---|---|---| | Bytes through app servers | yes | no | | File stored before validation | no, uploaded after commit | yes, already in the bucket | | Survives a failed validation | no, user picks the file again | yes, re-render the `signed_id` in a hidden field | | Abandoned files | none | blobs that never get attached | | Progress UI | browser only | `direct-upload:progress` events | The responsibilities that come with it: - **Orphans.** A user who uploads and closes the tab leaves an unattached blob. Schedule a sweep over `ActiveStorage::Blob.unattached` older than a day or two. - **An open endpoint.** `ActiveStorage::DirectUploadsController` is reachable by anyone by default. The guide shows subclassing it with your own `before_action` for authentication and routing to that subclass. - **Checks happen late.** Model validations on size and content type run when the form arrives, after the bytes are stored, so a rejected file must still be cleaned up. - **Custom clients.** `ActiveStorage.DirectUpload` can be used from your own JavaScript (drag and drop, or a Stimulus controller) with a delegate that hooks the upload request for progress. Direct uploads are the right default for large media or slow clients; small avatars on a low-traffic marketplace work fine as ordinary form uploads, without the orphan sweep and CORS setup.

  • How would you stop anonymous users from creating blobs through direct uploads?
    Subclass `ActiveStorage::DirectUploadsController`, add a `before_action` that checks the session or a token and answers `head :unauthorized`, route a path to it, and point the field's `data-direct-upload-url` (or the `DirectUpload` URL in custom JavaScript) at that route instead of `rails_direct_uploads_url`.
  • Why does a direct-uploaded file survive a failed validation when a normal upload does not?
    A normal upload is sent to the service in `after_commit`, so a failed save stores nothing and the browser cannot resend the file. A direct upload is stored before the form is submitted; re-rendering the form with a hidden field holding the blob's `signed_id` lets the next submit attach the same blob.

A direct upload is like a courier delivering a parcel straight to the warehouse while the office only files the delivery receipt: the clerk never carries the box, but someone has to check the warehouse for parcels whose receipts never arrived.

  • direct_upload: true streams the file through Rails faster using chunked encoding
  • After a direct upload the controller still receives an ActionDispatch::Http::UploadedFile
  • The direct uploads endpoint requires a signed-in user out of the box
  • Model validations stop an oversized direct upload before its bytes reach storage
  • Direct uploads need no cleanup because unattached blobs are deleted automatically