Comparison diagram of S3 Presigned POST policies versus presigned PUT uploads showing MIME enforcement, length handling, and signature verification

Routing client file uploads directly from web browsers to an object storage bucket eliminates web application server bottlenecks. Instead of proxying multi-gigabyte video files or disk archives through an application process—consuming application memory, CPU cycles, and network bandwidth—the client transmits bytes directly to the object store endpoint over HTTPS.

Historically, Amazon S3 provided two mechanisms for direct uploads: <b>Presigned POST policies</b> (designed for legacy <code>&lt;form method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt;</code> submissions) and <b>Presigned PUT URLs</b> (designed for REST clients and modern Fetch/XHR requests). While presigned POST policy documents offer declarative constraints such as <code>content-length-range</code> and <code>starts-with</code>, modern edge storage gateways frequently restrict or reject raw HTML form POST operations. Understanding these architectural differences ensures robust direct-to-bucket client integrations.

HTML Form POST policies vs Presigned PUT URLs

An S3 Presigned POST operation requires generating a base64-encoded JSON policy document containing an expiration timestamp and condition assertions. The form fields and policy are signed with AWS Signature Version 4. A standard policy specifies exact equality conditions or prefix boundaries:

json
{
  "expiration": "2026-11-20T12:00:00.000Z",
  "conditions": [
    {"bucket": "user-uploads"},
    ["starts-with", "$key", "uploads/2026/"],
    {"Content-Type": "image/png"},
    ["content-length-range", 1024, 10485760]
  ]
}

In theory, this allows a raw HTML form in a browser to submit a multipart body directly to <code>https://&lt;bucket&gt;.s3.amazonaws.com/</code> without JavaScript. However, in modern cloud architectures and edge object stores, <code>PostObject</code> is widely treated as legacy or explicitly unsupported. Testing direct browser multipart POST against modern S3-compatible gateways (including edge gateways like tport.space) yields <code>HTTP 403 AccessDenied</code> or <code>HTTP 501 NotImplemented</code> because the storage gateway routes only standard REST primitives (<code>PUT</code>, <code>GET</code>, <code>DELETE</code>, <code>HEAD</code>).

Consequently, production systems standardise on <b>Presigned PUT URLs</b> paired with the browser <code>fetch()</code> API. Rather than relying on a complex multipart form parser inside the storage gateway, presigned PUT signs the exact HTTP method, path, and request headers cryptographically.

MIME type enforcement: Cryptographic SigV4 header signing

A common security requirement is preventing users from uploading arbitrary or malicious file types (e.g., executing HTML/JavaScript in an SVG, or uploading binaries disguised as images). With Presigned PUT URLs, MIME type enforcement is achieved at the storage tier by including the <code>Content-Type</code> header inside the SigV4 <code>SignedHeaders</code> list during URL generation.

When the backend signs the URL with <code>ContentType='image/png'</code>, the storage engine calculates the canonical request hash incorporating that exact header. We tested three distinct client scenarios against live storage endpoints:

Test scenarioSigned Content-TypeClient sent Content-TypeHTTP statusGateway response
Matching MIMEimage/pngimage/png200 OKSignature verified; object committed to storage
Mismatched MIMEimage/pngtext/html403 ForbiddenSignatureDoesNotMatch; canonical hash mismatch
Omitted headerimage/png(None)403 ForbiddenSignatureDoesNotMatch; signed header absent from request
Path tamperingimage/pngimage/png (altered key)403 ForbiddenSignatureDoesNotMatch; canonical URI mismatch

Because SigV4 validates the entire canonical request before accepting object bytes, any modification by a malicious client—whether altering the MIME type to bypass validation, stripping headers, or rewriting the target storage key path—is rejected immediately at the edge. The upload never touches the bucket.

Size constraints: Content-length-range vs signed exact length

The primary functional difference between POST policies and presigned PUT URLs lies in size enforcement. Presigned POST policy documents support <code>content-length-range</code> (e.g., between 1 KiB and 10 MiB), enabling flexible file uploads where the exact size is unknown until the user selects the file in their browser.

Standard SigV4 presigned PUT URLs, by contrast, sign HTTP headers as exact key-value pairs. There is no concept of a mathematical range in HTTP request headers. As our live test confirmed, when a presigned PUT URL is generated without binding <code>Content-Length</code> in <code>SignedHeaders</code>, the gateway accepts any valid upload payload (tested at 1 KiB and 2 KiB) up to the storage system's maximum allowed single-part payload limit.

To strictly enforce file size limits when using presigned PUT URLs, architectures employ a two-layer control:

  • Pre-signing handshake: The browser selects the file, checks file.size, and requests a presigned URL from the application backend passing the exact byte count. The backend validates that file.size <= MAX_BYTES and signs Content-Length into the PUT URL headers. If the client subsequently attempts to send more or fewer bytes than stated, the upload fails with HTTP 403 SignatureDoesNotMatch or connection termination.
  • Client-side pre-flight guard: Modern JavaScript validates file extension, MIME type, and size before initiating the HTTP handshake, preventing wasted upload bandwidth.

Production implementation: Backend signing and browser client

Below is a complete, production-ready implementation using Python (Boto3) on the backend and native JavaScript Fetch on the client.

<b>Backend (Python FastAPI / Boto3):</b>

python
import boto3
from botocore.config import Config
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()
s3 = boto3.client(
    's3',
    endpoint_url='https://s3.tport.space',
    config=Config(signature_version='s3v4')
)

MAX_UPLOAD_SIZE = 15 * 1024 * 1024  # 15 MiB
ALLOWED_MIME_TYPES = {'image/png', 'image/jpeg', 'application/pdf'}

class UploadRequest(BaseModel):
    filename: str
    content_type: str
    content_length: int

@app.post('/api/uploads/presign')
def generate_upload_url(req: UploadRequest):
    if req.content_type not in ALLOWED_MIME_TYPES:
        raise HTTPException(status_code=400, detail="Unsupported MIME type")
    if req.content_length > MAX_UPLOAD_SIZE or req.content_length <= 0:
        raise HTTPException(status_code=400, detail="File size out of allowed bounds")

    # Generate unique storage key
    object_key = f"uploads/2026/{req.filename}"

    # Sign exact ContentType and ContentLength into SigV4 SignedHeaders
    url = s3.generate_presigned_url(
        ClientMethod='put_object',
        Params={
            'Bucket': 'production-assets',
            'Key': object_key,
            'ContentType': req.content_type,
            'ContentLength': req.content_length
        },
        ExpiresIn=900  # URL valid for 15 minutes
    )

    return {"upload_url": url, "key": object_key}

<b>Frontend (Modern Browser JavaScript):</b>

javascript
async function uploadFileDirectly(fileInput) {
  const file = fileInput.files[0];
  if (!file) return;

  // 1. Request presigned PUT URL from application server
  const metaResponse = await fetch('/api/uploads/presign', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      filename: file.name,
      content_type: file.type,
      content_length: file.size
    })
  });

  if (!metaResponse.ok) {
    const err = await metaResponse.json();
    throw new Error('Presign failed: ' + err.detail);
  }

  const { upload_url } = await metaResponse.json();

  // 2. Direct PUT to S3 endpoint with exact matching headers
  const uploadResponse = await fetch(upload_url, {
    method: 'PUT',
    headers: {
      'Content-Type': file.type,
      'Content-Length': file.size.toString()
    },
    body: file
  });

  if (!uploadResponse.ok) {
    throw new Error(`Upload rejected with HTTP ${uploadResponse.status}`);
  }

  console.log('Upload successfully committed to storage!');
}

CORS requirements for direct browser uploads

Because the browser initiates a cross-origin HTTP <code>PUT</code> from the web application domain (e.g., <code>https://app.example.com</code>) to the storage endpoint (e.g., <code>https://s3.tport.space</code>), the target bucket must have an active CORS configuration. The CORS policy must allow the <code>PUT</code> verb and explicitly expose headers:

json
[
  {
    "AllowedOrigins": ["https://app.example.com"],
    "AllowedMethods": ["PUT"],
    "AllowedHeaders": ["Content-Type", "Content-Length"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3600
  }
]

Architectural guidelines

  • Avoid POST policies on S3-compatible backends: PostObject is unsupported across numerous edge storage gateways. Standardising on Presigned PUT provides compatibility across AWS S3, Cloudflare R2, MinIO, and tport.space.
  • Always sign Content-Type: Omission allows clients to upload malicious executables or scripts under arbitrary MIME classifications. Signing ContentType guarantees that the uploaded byte stream matches the declared format.
  • Set tight URL expiration windows: Configure presigned upload URLs with short TTLs (typically 5 to 15 minutes). Once an upload completes, the URL should lapse to prevent reuse.
  • Validate magic bytes post-upload: If user-uploaded images or documents are subsequently served publicly, trigger an asynchronous background worker to verify magic bytes before publishing.