Files in Apex are tricky because of heap limits (6 MB sync, 12 MB async) and request size limits.
Salesforce file primitives: Blob (binary, capped at heap), ContentVersion (versioned file record), ContentDocument / ContentDocumentLink (parent + links).
Upload patterns:
- Direct upload via REST API (file transferred to Salesforce, not through Apex): external system POSTs to
/services/data/vXX/sobjects/ContentVersion/with multipart/form-data. Salesforce stores it; your Apex doesn't see the binary. Best for large files.
- Chunked upload through Apex: client splits file into chunks (each <6 MB), sends one at a time. Apex appends. Heap concerns — concatenating Blobs has the same 6 MB cap.
- Salesforce Files Connect or external storage: files >2 GB go to S3, Box, SharePoint via Files Connect. Salesforce holds metadata; binary lives elsewhere.
Download patterns: for files near heap limit, return a redirect URL pointing to the file's direct ContentVersion endpoint, let client download from there.
Practical advice: files >2 MB never load into Apex heap; files <2 MB Apex Blob is fine; use async (Batch/Queueable) for any heavy file operation (12 MB heap doubles headroom); avoid holding multiple large Blobs simultaneously.
