Requests, files, and servers

Handle file uploads

Validate upload purpose, size, type, content, storage, permissions, and delivery without trusting filenames or browser-provided metadata.

8 minute lesson

~~~

An upload is untrusted bytes plus untrusted metadata. Treat both parts as hostile until the server checks them.

Set strict size limits, inspect content with an appropriate parser, generate the storage name, and keep files outside executable application paths. Serve through a separate download path with deliberate content type and disposition. Scan when the risk justifies it.

A file named avatar.png carries HTML and script. If the server trusts the name and serves it inline from the application origin, the upload becomes active content.

Deep scanning adds time and can still miss new formats. Start with a narrow accepted format, strict size, verified parsing, generated storage names, and safe download headers.

Upload a valid image, an oversized image, HTML renamed as PNG, a malformed image, and two files with the same name. Record the decision, stored name, detected type, and response headers for every case.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →