
Editorial illustration.
Originally published 23 June 2023; rewritten and reviewed on 15 October 2026.
The browser shows a filename and the progress bar moves to the end. That proves some bytes travelled, but it does not establish that the server accepted the document for its intended use. In too many ASP.NET projects I have inherited, the client-side upload widget was polished first while the controller action simply trusted Request.Files[0] and wrote it straight to disk.
Define the server boundary first. Once the controller’s contract, limits, and storage rules are clear, wiring up the JavaScript side takes ten minutes.
Send the file with the form’s security context
A clean browser upload uses FormData and fetch, letting the browser construct the multipart/form-data boundary automatically. A common mistake is manually adding 'Content-Type': 'multipart/form-data' to the headers object—doing that strips the boundary parameter and causes ASP.NET model binding to receive a null file.
const form = document.querySelector('#uploadForm');
const input = document.querySelector('#fileInput');
const token = form.querySelector('input[name="__RequestVerificationToken"]').value;
if (!input.files.length) {
throw new Error('Choose a file first.');
}
const data = new FormData();
data.append('file', input.files[0]);
data.append('__RequestVerificationToken', token);
const response = await fetch('/documents/upload', {
method: 'POST',
body: data,
credentials: 'same-origin'
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.message || `Upload failed (${response.status}).`);
}
const result = await response.json();
If you need a real-time percentage progress bar for large PDFs or videos, fetch still does not expose upload progress events reliably across browsers. Use XMLHttpRequest with xhr.upload.onprogress for that specific requirement, and keep the exact same FormData payload and antiforgery token.
Classic ASP.NET MVC 5 and ASP.NET Core handle antiforgery tokens slightly differently. In MVC 5, [ValidateAntiForgeryToken] expects __RequestVerificationToken inside the form body (which FormData handles nicely) alongside the cookie. In ASP.NET Core, you can either send it in FormData or pass it via a custom header such as RequestVerificationToken configured in AddAntiforgery.
Enforce limits at both the web server and the action
Before your C# code even runs, IIS or Kestrel may reject a large payload with a cryptic 404.13 or 413 error. On classic ASP.NET MVC hosted on IIS, you must align both system.web/httpRuntime and system.webServer/security/requestFiltering in Web.config:
<system.web>
<!-- Size in kilobytes (10 MB = 10240 KB) -->
<httpRuntime targetFramework="4.8" maxRequestLength="10240" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- Size in bytes (10 MB = 10485760 bytes) -->
<requestLimits maxAllowedContentLength="10485760" />
</requestFiltering>
</security>
</system.webServer>
On ASP.NET Core, apply [RequestSizeLimit(10_485_760)] and [RequestFormLimits(MultipartBodyLengthLimit = 10_485_760)] directly on the controller action so you do not raise limits globally for every endpoint.
Validate and store safely in C#
Authenticate and authorise the request, enforce limits, and inspect the permitted format on the server. Never trust file.FileName as a filesystem path or file.ContentType as proof of what is inside the file—both are user-controlled strings.
Here is a practical ASP.NET Core MVC action pattern that checks size, extension, and basic file-header bytes before writing to a non-executable directory:
[HttpPost]
[ValidateAntiForgeryToken]
[RequestSizeLimit(10_485_760)]
public async Task<IActionResult> Upload(IFormFile file, CancellationToken ct)
{
if (file is null || file.Length == 0)
return BadRequest(new { message = "File is empty." });
var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
if (ext != ".pdf" && ext != ".png")
return StatusCode(StatusCodes.Status415UnsupportedMediaType,
new { message = "Only PDF and PNG files are allowed." });
// Read header bytes without trusting ContentType
byte[] header = new byte[4];
using (var stream = file.OpenReadStream())
{
int read = await stream.ReadAsync(header.AsMemory(0, 4), ct);
if (read < 4 || !MatchesSignature(ext, header))
return BadRequest(new { message = "File content does not match extension." });
}
var safeName = $"{Guid.NewGuid():N}{ext}";
var uploadRoot = Path.Combine(_env.ContentRootPath, "App_Data", "Uploads");
Directory.CreateDirectory(uploadRoot);
var targetPath = Path.Combine(uploadRoot, safeName);
await using (var fs = System.IO.File.Create(targetPath))
{
await file.CopyToAsync(fs, ct);
}
// Save safeName + original Path.GetFileName(file.FileName) in DB
return Ok(new { documentId = safeName, status = "received" });
}
The original sample from 2023 saved a file straight into a public folder using its supplied filename. That opens the door to path traversal (../../), overwrites, and direct URL execution if someone uploads an .aspx or .svg with embedded script. Keep the original filename strictly as display metadata in your database, and serve downloads through an authorised controller action with Content-Disposition: attachment.
Communicate acceptance accurately
Return a document identifier and an honest processing state. If antivirus scanning, PDF thumbnailing, or Cloudflare R2 syncing happens in a background worker, return 202 Accepted with "status": "processing" rather than telling the user the file is "ready". Handle cancellation and retries gracefully—if the user clicks Upload twice on a slow Malaysian mobile connection, use an idempotency key or clean up partial temp files rather than leaving orphan blobs in storage.
Test empty uploads, oversized files, a .exe renamed to .pdf, unauthenticated requests, and mid-upload tab closes. The feature is finished when users know unambiguously whether their document landed safely and your logs let support trace every failed attempt.