---
title: Limit Upload File Size And Count
impact: MEDIUM
impactDescription: prevents denial of service attacks
tags: upload, file-size, dos, limits, security
---

## Limit Upload File Size And Count

Unlimited uploads can exhaust disk space and memory, causing denial of service.

**Incorrect (no limits):**

```go
func UploadHandler(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(32 << 20) // 32MB in memory, but no total limit
    file, _, _ := r.FormFile("file")
}
```

**Correct (enforce limits):**

```go
func UploadHandler(w http.ResponseWriter, r *http.Request) {
    // 1. Limit total request body size
    r.Body = http.MaxBytesReader(w, r.Body, 5<<20) // 5MB limit
    
    err := r.ParseMultipartForm(5 << 20)
    if err != nil {
        http.Error(w, "File too large or invalid request", http.StatusRequestEntityTooLarge)
        return
    }
    
    // 2. Validate file type
    file, header, _ := r.FormFile("file")
    buffer := make([]byte, 512)
    file.Read(buffer)
    contentType := http.DetectContentType(buffer)
    
    allowedTypes := map[string]bool{
        "image/jpeg": true,
        "image/png":  true,
        "application/pdf": true,
    }
    
    if !allowedTypes[contentType] {
        http.Error(w, "Invalid file type", 400)
        return
    }
}
```

**Recommended limits:**
- Images: 5-10MB
- Documents: 10-50MB
- Max total request size: 100MB

**Tools:** `http.MaxBytesReader`, NGINX `client_max_body_size`
