File uploads from browser to storage and back

Intermediate · 12 min

Let Taskboard users attach files with presigned URLs: the browser uploads straight to object storage, the API records it, and downloads use short-lived links.

Before thisPagination, filtering and search end to end

Good Morning Developers · 80 min

File uploads from browser to storage and back

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Good Morning DevelopersReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Files belong in object storage, and the database holds a key and metadata that point to them.
  • A presigned URL lets the browser upload directly to storage for a short time without ever holding storage credentials.
  • The upload is three steps, not one: ask the API for a slot, send the bytes to storage, then tell the API it is done so it can check and record the file.
  • A presigned URL signs only what you tell it to, and in my test the Content-Type header was not part of the signature unless I asked for it.
  • Never trust the filename, type or size the client reports, and serve downloads through short-lived links rather than public buckets.

Files are not rows

Taskboard lets people attach files to a task. The first idea is to treat a file like any other value: send it to the API in a form, and have the API save it. That works on day one and causes trouble later.

  • Putting file bytes in the database makes backups huge and queries slower, for data you never query.
  • Writing them to the API server’s disk loses them when the server is replaced, and breaks as soon as you run two servers, because the file is on only one of them.
  • Streaming every upload through your API ties up your server for the duration of a slow upload, and you pay for the bandwidth twice.

The standard answer is object storage: Amazon S3, Cloudflare R2, Google Cloud Storage, or MinIO on your own machine. It stores large files durably and serves them cheaply. The database keeps only a pointer: that is why the attachments table has a storage_key and not a bytes column. The backend roadmap covers the storage side in file uploads and object storage. This lesson follows the file across layers.

The three-step upload

The browser should send the bytes straight to storage. But storage needs to know the request is allowed, and you can’t put your storage credentials in the browser. The answer is a presigned URL: your API, which holds the credentials, signs a URL for one specific upload. The signature is in the URL itself, and it expires. Whoever holds the URL can do exactly that one thing until it expires.

So an upload is three steps:

Browser                     API                        Storage
   | 1. "I want to attach      |                           |
   |    photo.png, 80 KB"      |                           |
   |-------------------------->|  checks: signed in, may   |
   |                           |  edit this task, type and |
   |                           |  size allowed             |
   |<-- key + presigned PUT ---|                           |
   | 2. PUT bytes to that URL  |                           |
   |-------------------------------------------------------->|
   |<------------------------------------------- 200 --------|
   | 3. "done, key is X"       |                           |
   |-------------------------->|  checks the object exists |
   |                           |  inserts attachments row  |
   |<-- the attachment --------|                           |

Step 1: ask for a slot. The client sends the filename, content type and size. The API checks that the person is signed in, that they may edit this task, and that the type and size are acceptable. It picks the storage key itself and returns a presigned URL.

Step 2: upload. The browser sends the file with a plain PUT to the presigned URL. Your API isn’t involved.

Step 3: confirm. The API never saw the bytes, so it can’t assume the upload happened. The client calls back, the API checks the object exists in storage, and only then inserts the row into attachments. A file that was uploaded but never confirmed is invisible and can be cleaned up later.

Making the URL

Signing happens locally, with the credentials and no network call. I ran this against a fake endpoint (AWS SDK client-s3 3.1175.0 with the request presigner at the same version), so it proves the URL’s shape and not an actual upload:

const s3 = new S3Client({
  region: "us-east-1",
  endpoint: "http://localhost:9000",   // MinIO from the compose file
  forcePathStyle: true,
  credentials: { accessKeyId: "dev", secretAccessKey: "devdevdev" },
});

const key = `attachments/${randomUUID()}`;
const url = await getSignedUrl(
  s3,
  new PutObjectCommand({ Bucket: "taskboard", Key: key, ContentType: "image/png" }),
  { expiresIn: 300 },
);

The result is http://localhost:9000/taskboard/attachments/<uuid> followed by a query string carrying the algorithm, credential, date, expiry (X-Amz-Expires=300) and signature.

Three choices in there deserve explanation:

  • You pick the key, never the client. A random UUID means a user can’t overwrite another user’s file or write outside the prefix. The original filename lives in the database, not in the key.
  • expiresIn: 300. Five minutes is plenty to start an upload. A long expiry turns a leaked URL into a long-lived hole.
  • forcePathStyle is needed for MinIO on localhost. Real S3 doesn’t need it.

What the signature actually covers

Here is something I did not expect. I asked for ContentType: "image/png" and then looked at which headers the signature covered:

put with ContentType:          signed headers: host
put with ContentType and Len:  signed headers: content-length;host
put with signableHeaders:      signed headers: content-type;host

By default, only host was signed. The content type I specified was not part of the signature, so the browser could upload a file with a different type and the URL would still be valid. Adding ContentLength put content-length in the signature. And passing signableHeaders: new Set(["content-type"]) put the content type in. That is a behaviour of this SDK version as I observed it, so check the one you use rather than assuming.

The lesson: a presigned URL authorises exactly what you signed and nothing more. If a constraint matters, such as “this must be a PNG under 5 MB”, either sign it in, or check it in step 3 by asking storage for the object’s real size and type. Do the second regardless.

Never trust the client’s description

The browser tells you a name, a type and a size. All three are claims.

  • Size. Validate in step 1 against a limit, and verify the real size in step 3.
  • Type. The Content-Type is whatever the client wrote. An .exe can be sent as image/png. For files you later serve to other users, restrict the allowed types, and don’t render an uploaded file in a way that executes it.
  • Name. Treat ../../etc/passwd as a string to store, not a path to open. Because the key is your UUID, the name never touches a path.

The attachments table from the schema lesson already has CHECK (size_bytes > 0) and a UNIQUE storage key, so a bug in step 3 can’t record a zero-byte file or the same object twice.

Downloads and cleanup

To show the file, don’t make the bucket public. When someone opens the task, the API returns a short-lived presigned GET URL for each attachment, after checking they may see the task. The expiry means a link pasted into a chat stops working soon. You can also set ResponseContentDisposition so the browser downloads the file instead of displaying it.

Failures leave orphans. A person starts an upload and closes the tab, so there’s an object with no row, or a row exists and the object was later deleted. Plan a small cleanup job for unconfirmed uploads, which storage lifecycle rules can often do for you. Background jobs get their own lesson in background work and email from a feature.

Where this crosses layers

Every seam shows up here:

  • Browser to storage needs CORS configured on the bucket, because the page’s origin differs from storage. The browser will block the PUT otherwise, and the error looks like a network failure. CORS and cross-origin setups covers it.
  • API to storage uses credentials that must stay in the server’s environment, per the secrets lesson.
  • API to database records the pointer and enforces that only members see it.
  • Client shows progress, handles failure in step 2 separately from steps 1 and 3, and retries.

What I did not run: an actual upload. Docker wasn’t available, so MinIO never started, and I haven’t watched a browser PUT succeed or the bucket CORS rules take effect. The signing output above is real. The flow around it is the standard presigned-URL pattern, and you should test each step against your own storage.

What the video covers

Good Morning Developers’ “Upload a File Directly To S3 From The Browser (w/Express.js Help)” is a long, 80-minute build, published November 2023. This lesson embeds only the first 11 minutes 42 seconds: the chapters “How This Works (Drawing)” at 0:00, “Steps” at 4:55 and “Final Demo and Repo” at 7:56. The description says the Express back end generates a signed link with the AWS SDK and the front end sends the file directly to S3, which avoids the processing, disk space and bandwidth of using Express as a middleman. That is the presigned-URL flow this lesson teaches. The rest of the video, a front-end and Express file walk-through, is left out, and the description promotes the creator’s Udemy course. The bucket-CORS, content-type signing and confirm-step parts are my own. I could not read a transcript, so I rely on the title, description and chapters. TomDoesTech’s presigned PUT video and Academind’s S3 and R2 with React video are linked as second views.

Where this fits

That finishes the data layer: a schema with rules, typed queries, screens that fetch efficiently, lists that page correctly, and files that live in the right place. The database now holds what the app needs, and the next group decides how the client reaches it. It starts with designing endpoints for the UI.

Check yourself

  1. 01Why not store uploaded files in a database column or on the API server's disk?

    Database columns bloat backups and slow queries, and a server's local disk disappears when instances are replaced or scaled. Object storage is built for large, durable files.

  2. 02What does the browser need in order to upload to storage?

    A presigned URL from the API. It carries a signature and an expiry, so the browser can upload one object for a few minutes without any credentials.

  3. 03Why does the client tell the API when the upload is finished?

    Because the API never saw the bytes. It must verify the object exists and is acceptable, then insert the attachment row that makes it visible in the app.

  4. 04What did I find about Content-Type in a presigned PUT URL?

    By default only the host header was signed, so the type was not enforced. Passing signableHeaders for content-type added it to the signature.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark