In this article i will show you how you can perform file upload in asp.net 6/MVC application using HTML input file control using c#.net.
In my previous articles:
Registration and Login Form Creation In Asp.net Core 6 Using C#.Net From Database, Validate User Id and Password From MS SQL Database in Asp.Net Core Using C#, Login Form In Asp.net Core 6 Using C# From Ms Sql Server Database, How To Connect MS SQL Server Database in Asp.net Core MVC Using C#.Net
@{ ViewData["Title"] = "Upload Page"; } @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" })) { <div class="text-center"> <h1 class="font-weight-bold">Upload File</h1> <p style="color:red;font-weight:bold;"> @ViewBag.Message </p> <input type="file" name="formFile" /> <input type="submit" value="Upload" /> </div> } |
[HttpGet] public IActionResult Index() { return View(); } [HttpPost] public IActionResult Index(IFormFile formFile) { try { string fileName = formFile.FileName; fileName = Path.GetFileName(fileName); string uploadpath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", fileName); var stream = new FileStream(uploadpath, FileMode.Create); formFile.CopyToAsync(stream); ViewBag.Message = "File uploaded successfully."; } catch { ViewBag.Message = "Error while uploading the files."; } return View(); } |
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Diagnostics; using System.IO; |
Now select the file.
After selecting file click on upload button. I have put a break point to show you the file detail.
Here in above code you can check that we are getting all the detail of the file. Now press F5 and check the output.
Now at last we will check the wwwroot ->image folder for our uploaded file.
0 comments:
Please let me know your view