Wednesday, 26 January 2022

Asp.Net Core 6: Upload and Save Image Detail in Database By Entity Framework Using C# In .Net Core

1/26/2022 - By Pranav Singh 0

In this article i will show you how you can upload the file in asp.net core 6 and save the file detail into the data base using c#.net. 


Other related articles: Asp.Net Core 6: Upload and Preview Image Using C# In .Net Core (wwwroot)Upload / Save File in User Created Folder in Asp.Net Core 6/MVC in C#.NetAsp.Net Core 6 : Rename / Change File or Image Name  and Upload in wwwroot Using C#.Net,  ASP.NET Core 6 : Ajax Upload File( Without Page Refresh) To wwwroot Folder in Using C#.Net , jQueryAsp.Net Core 6 : Upload File  in User Created Folder (Folder Outside wwwroot) Using C#.


Now for this article first we will create a new asp.net core 6 application and create  a new table in sql server database. 


image data in asp.net core

Now we will make connection to the data base using entity framework. Do do this you need to execute the below command which is scamfold command. 


If you are making new connection on that case you need to run the below command.

Scaffold-DbContext "Server=..\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir data 

If you already have connection and want to update the DB context, run the blow code.

Scaffold-DbContext "Server=..\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir data -force

Now in our application we will create the view and add the below code into the 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" /><br />

        @if (ViewBag.Image != null)

        {

            <b>You have uploaded</b><br />

            <img src="@ViewBag.Image" width="200px" height="200px" />

        }

    </div>

}


In above code i have added the form tag. In this tag you must add the enctype. If you don't add the enctype you will not be able to get the file detail at controller end ones you post the form. Now we will write the code in controller post method.


[HttpGet]

        public IActionResult Index()

        {

 

            return View();

        }

        [HttpPost]

        public IActionResult Index(IFormFile formFile)

        {

            try

            {

                string fileName = Path.GetFileName(formFile.FileName);

                string uploadfilepath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", fileName);

                var filestream = new FileStream(uploadfilepath, FileMode.Create);

                formFile.CopyToAsync(filestream); 

                //---------Start Save Data to DB-----------------

                string uploadedDBpath = "images\\" + fileName;

                TestDBContext testDBContext = new TestDBContext();

                var uploadImage = new UploadImage()

                {

                    CreatedDate = DateTime.Now,

                    ImagePath = uploadedDBpath

                };

                testDBContext.UploadImages.Add(uploadImage);

                testDBContext.SaveChanges();

                ViewBag.Image = uploadedDBpath;

                //---------End Save Data to DB-----------------

                ViewBag.Message = "File uploaded & saved successfully.";

            }

            catch (Exception ex)

            {

                ViewBag.Message = "Error while uploading the files.";

            }

            return View();

        }


In above code first i have uploaded the file and after uploading the file i have capture the name of the file stored in the variable. After string he value i have saved the detail into the database.  Now lets run the code and and check the output. Here is the folder where we have uploaded the file.


uploaded image

Now here is the database whether the file path have been stored.



Now here s the final output.

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top