Skip to main content

Upload Excel File in .Net 6 Application

 Uploading files in a .NET 6 application is a common task that can be easily achieved using the built-in File Upload control. Here are the steps to upload a file in a .NET 6 application:

  1. Add a File Upload control to the page where you want to allow file uploads. You can use the HTML input element with type="file" to create a File Upload control.
html
<input type="file" name="file" />
  1. In the controller action that handles the form submission, get the uploaded file using the Request.Form.Files property. You can then save the file to disk or process it as needed.
csharp
[HttpPost] public async Task<IActionResult> Upload(IFormFile file) { if (file != null && file.Length > 0) { // Save the file to disk or process it as needed // Example: save the file to a folder named "uploads" in the application root var path = Path.Combine(Directory.GetCurrentDirectory(), "uploads", file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } // Return a success response return Ok(); } // If no file was uploaded, return a bad request response return BadRequest(); }
  1. When the form is submitted, the browser will send a POST request to the controller action. The uploaded file will be available in the file parameter of the action method.

  2. Save the uploaded file to a location on the server or process it as needed. In the example above, the file is saved to a folder named "uploads" in the application root.

Note that you can also add validation to the file upload control to restrict the types and sizes of files that can be uploaded. This can be done using the Accept and MaxFileSize properties of the File Upload control.

Comments