In this article i will show you how you can upload file in asp.net core 6 using c#.net in your wwwroot folder or any wwwroot folder or images folder present in wwwroot folder in asp.net core 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
So for this article first we will create a new asp.net core project and in our wwwroot folder we will create a folder named as Images.
After this we will create a controller class file and create a view. Please check the below code of view.
@{ 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; |
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.
0 comments:
Please let me know your view