In this article i will sow you how you can upload the image file in asp.net core 6 or mvc application using c#.net and display the upload image preview.
Other Articles: Enum Return String Value C#, Asp.Net Core 6: How to Search/Find Data Between Two Dates In MS Sql , Linq, C#.net, Asp.net Core 6: Access/Read/Pass TextBox and TextboxFor Value From View To Controller In C#.Net, XML File Read(Parse) and Display In Table/Tabular Format in ASP.Net Core 6 / MVC Using C#.Net, ASP.NET Core 6 : Ajax Upload File( Without Page Refresh) To wwwroot Folder in Using C#.Net , jQuery.
Now for this article first we will create a new asp.net core 6 mvc application and add a controller class file. In controller we will create an httpget action method.
[HttpGet] public IActionResult Index() { return View(); } |
Now we will build the view, and add the below code into the view.
@{
ViewData["Title"] = "Home Page"; } @using (Html.BeginForm("Index", "Home",
FormMethod.Post, new {
@enctype = "multipart/form-data" })) {
<span style="font-weight:bold;">Upload File</span>
<br />
<span style="color:red;">@ViewBag.Message</span>
<br />
<input type="file" name="formFile" />
<input type="submit" value="Submit" />
<br />
<br />
@if (ViewBag.ImageURL != null)
{ <img src="@ViewBag.ImageURL" width="300px" height="200px" />
} } |
In above code we need to add the added the form tag. In this form tab you must add the @enctype = "multipart/form-data". Now have look of the input file type control. Here you must remember the name of the control because we are going to user this name in controller to access the detail of the uploaded file. Now we will add the controller httppost code.
[HttpPost] public IActionResult Index(IFormFile formFile) { try { string fileName =
Path.GetFileName(formFile.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."; ViewBag.ImageURL = "images\\" + fileName; } catch { ViewBag.Message = "Error while uploading the files."; } return View(); } |
In above code just check the IFformFile interface, the parameter name is same as the file input control. If this is not same as file input control you will not be able to get the uploaded file at controller end. After successful upload i have stored the file detail in ViewBag and bind it to image control. Here you need to take care one thing, don't pass wwwroot folder in the image path.
Now run the code and check the output.
0 comments:
Please let me know your view