# How do I accept file uploads from users safely?
Source: https://ruststudio.org/community/t/87/how-do-i-accept-file-uploads-from-users-safely
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, getrandom 0.2.17, hex 0.4.3, Windows 11
Category: Help and questions | Kind: FAQ | Tags: security, uploads, web | Views: 0

## Short answer
Limit the size, decide the type by looking at the file's first bytes, keep only types you expect, store the file under a random name you generate with an extension you choose, and keep uploads outside any folder the web server runs or serves directly. Never use the client's file name or Content-Type.

## Answer
## Answer
Everything about an upload is chosen by the sender: the name, the declared type, the contents. A safe handler therefore decides each of these itself.

| Property | Do not trust | Do instead |
|---|---|---|
| Size | `Content-Length` | A byte limit while reading |
| Type | file extension, `Content-Type` | Check the first bytes ("magic numbers") against an allow-list |
| Name | the client's file name | Generate a random name; choose the extension from the detected type |
| Location | a path from the request | A fixed folder outside the web root |

```rust title=src/main.rs
const MAX_BYTES: usize = 2 * 1024 * 1024;

/// Decide the file type from the first bytes, never from the name or the Content-Type header.
fn sniff(data: &[u8]) -> Option<&'static str> {
    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
        Some("png")
    } else if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
        Some("jpg")
    } else {
        None
    }
}

/// Returns the name to store the file under: random, with an extension we chose.
fn accept_upload(data: &[u8]) -> Result<String, &'static str> {
    if data.is_empty() || data.len() > MAX_BYTES {
        return Err("empty or too large");
    }
    let ext = sniff(data).ok_or("not a PNG or JPEG")?;
    let mut id = [0u8; 16];
    getrandom::getrandom(&mut id).map_err(|_| "no randomness")?;
    Ok(format!("{}.{ext}", hex::encode(id)))
}

fn main() {
    let png = [&b"\x89PNG\r\n\x1a\n"[..], &[0u8; 20]].concat();
    let fake = b"<script>alert(1)</script>"; // sent with a name like "photo.png"
    println!("{:?}", accept_upload(&png).map(|n| (n.len(), n.ends_with(".png"))));
    println!("{:?}", accept_upload(fake));
    println!("{:?}", accept_upload(&vec![0xFF; MAX_BYTES + 1]));
}
```

```text
Ok((36, true))
Err("not a PNG or JPEG")
Err("empty or too large")
```

The output shows a genuine PNG header accepted under a name of 36 characters (32 hex characters plus `.png`), a script presented as an image refused, and an oversized file refused.

## How to do it
1. Enforce the size limit in the web framework before the body reaches your code.
2. Detect the type from the content and allow only the types the feature needs.
3. Generate the stored name; keep the original name, if you need it, only as display text, escaped on output.
4. Store files outside the web root, serve them through a handler that sets the right `Content-Type` and `X-Content-Type-Options: nosniff`, and for downloads of non-image types add `Content-Disposition: attachment`.
5. For images, re-encode them with an image library if you need to remove embedded data, and set a maximum width and height so a small file cannot expand into a huge bitmap.
6. Scan or sandbox documents when the use case requires it, and never run uploaded files.

## Common mistakes
- Checking the extension only: `shell.png` can contain anything.
- Letting the web server execute files in the upload folder.
- Magic-number checks treated as proof the file is harmless: a valid image header can be followed by anything. The check narrows the type; it does not make a file safe.
- Reading the entire upload into memory before checking its size.

## Related questions
### Where do temporary files go while the upload is processed?
In a private temporary file with a random name; see the thread on temporary files.

### Should I store uploads in the database instead?
It avoids file-system path problems but makes the database larger and slower for big files. The other checks (size, type, name) still apply.

## Sources
- OWASP File Upload Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html
- MDN, `X-Content-Type-Options`: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Content-Type-Options
