Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
dhana ganiRank #1,083 · 1.8K reputationPosted Oct 26, 2026, 3:02 AM EDT
For uploading a document to the server in .NET, the implementation depends on whether you are using ASP.NET Web Forms, ASP.NET MVC, or ASP.NET Core MVC.
1. ASP.NET MVC
In MVC, use an HTML file input with
enctype="multipart/form-data"and receive the uploaded file through the controller action.[HttpPost] public ActionResult Upload(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { string extension = Path.GetExtension(file.FileName); // Validate the extension and file size. // Generate a unique server-side filename. string fileName = Guid.NewGuid().ToString("N") + extension; string folder = Server.MapPath("~/Uploads/"); Directory.CreateDirectory(folder); file.SaveAs(Path.Combine(folder, fileName)); return Content("File uploaded successfully."); } return Content("Please select a file."); }2. ASP.NET Core MVC
In ASP.NET Core MVC, use
IFormFileto receive the uploaded file.[HttpPost] public async Task Upload(IFormFile file) { if (file == null || file.Length == 0) return BadRequest("Please select a file."); // Validate the file type and size before saving. string extension = Path.GetExtension(file.FileName); string fileName = Guid.NewGuid().ToString("N") + extension; string folder = Path.Combine( Directory.GetCurrentDirectory(), "UploadedFiles"); Directory.CreateDirectory(folder); string filePath = Path.Combine(folder, fileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } return Ok("File uploaded successfully."); }For both approaches, the form should use
method="post"andenctype="multipart/form-data".Security considerations:
Allow only the required file types and enforce a maximum file size.
Do not trust the original filename or extension alone; validate the file content as appropriate.
Generate a unique filename on the server.
Store uploaded documents outside the publicly accessible web root when possible, and enforce authorization when retrieving them.
Official Microsoft references
ASP.NET MVC: Upload files in ASP.NET MVC
ASP.NET Core MVC: Upload files in ASP.NET Core
These references provide additional examples and security guidance.
Jesse Johnson32 reputationPosted Oct 27, 2026, 12:20 AM EDT
I found the code examples for file uploads really helpful! But I'm curious—how do you handle large files or upload limits in .NET? Any best practices to share?