Single File Upload in Forms in ASP.NET Core MVC


On the Visual Studio, create new ASP.NET Core MVC Web Application project

Select Empty Template

Click Ok button to Finish

Create new folder named images in wwwroot folder.




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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreMVCWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

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

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Product}/{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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreMVCWithRealApps.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 System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using LearnASPNETCoreMVCWithRealApps.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
    [Route("product")]
    public class ProductController : Controller
    {
        [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(Directory.GetCurrentDirectory(), "wwwroot/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 razor views as below:

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

@{
    Layout = null;
}

@model LearnASPNETCoreMVCWithRealApps.Models.Product

<!DOCTYPE html>

<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:

@{
    Layout = null;
}

<!DOCTYPE html>

<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

I recommend you refer to the books below to learn more about the knowledge in this article: