Single File Upload in Forms in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish




Create new folder named images in wwwroot folder.

Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}");
            });
        }
    }
}

Create new folder named Models. In Models folder, create new entities class as below:

Create new class named Product.cs as below:

namespace LearnASPNETCoreMVC5.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public string Photo { get; set; }
    }
}




Create new folder named Controllers. In this folder, create new controller named ProductController.cs as below:

using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("product")]
    public class ProductController : Controller
    {
        private IWebHostEnvironment webHostEnvironment;

        public ProductController(IWebHostEnvironment _webHostEnvironment)
        {
            webHostEnvironment = _webHostEnvironment;
        }

        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            return View("Index", new Product());
        }

        [Route("save")]
        [HttpPost]
        public IActionResult Save(Product product, IFormFile photo)
        {
            if (photo == null || photo.Length == 0)
            {
                return Content("File not selected");
            }
            else
            {
                var path = Path.Combine(this.ihostingEnvironment.WebRootPath, "images", photo.FileName);
                var stream = new FileStream(path, FileMode.Create);
                photo.CopyToAsync(stream);
                product.Photo = photo.FileName;
            }
            ViewBag.product = product;
            return View("Success");
        }

    }
}

Create new folder named Views. In this folder, create new folder named Product and add new views as below:

In Product folder, create new view named Index.cshtml as below:

@model LearnASPNETCoreMVC5.Models.Product

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <form asp-controller="product" asp-action="save" method="post" enctype="multipart/form-data">
        <table cellpadding="2" cellspacing="2">
            <tr>
                <td>Id</td>
                <td>
                    <input type="text" asp-for="Id" />
                </td>
            </tr>
            <tr>
                <td>Name</td>
                <td>
                    <input type="text" asp-for="Name" />
                </td>
            </tr>
            <tr>
                <td>Price</td>
                <td>
                    <input type="text" asp-for="Price" />
                </td>
            </tr>
            <tr>
                <td>Photo</td>
                <td>
                    <input type="file" name="photo" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" value="Save" /></td>
            </tr>
        </table>
    </form>

</body>
</html>




In Product folder, create new view named Success.cshtml as below:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Success</title>
</head>
<body>

    <h3>Product Info</h3>
    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <td>Id</td>
            <td>@ViewBag.product.Id</td>
        </tr>
        <tr>
            <td>Name</td>
            <td>@ViewBag.product.Name</td>
        </tr>
        <tr>
            <td>Price</td>
            <td>@ViewBag.product.Price</td>
        </tr>
        <tr>
            <td>Photo</td>
            <td><img src="~/images/@ViewBag.product.Photo" width="120" /></td>
        </tr>
    </table>

</body>
</html>

Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers







Access Index action in Product controller with following url: http://localhost:48982

Output

Click Save button submit form to Save action in Product controller with following url: http://localhost:48982/product/save

Output