How to upload file in ASP.NET Core MVC, File uploading concept in .net core MVC

0

 How to  upload file in  ASP.NET Core MVC, File uploading concept in .NET  core MVC:-

It is used to upload any external content such as audio, video, text and doc file under project.

Microsoft provide IFormFile class to handle file uploading operation


Step by Step Implementation


1)  Create Project


2)  Create FileUpload.cs class under Models folder

public class FileUpload

    {

        public IFormFile FormFile { set; get; }

    }


3)  Create FileUploadingController Class


using Microsoft.AspNetCore.Mvc;

using CodeFirstExample.Models;

using Microsoft.Extensions.Hosting.Internal;


namespace CodeFirstExample.Controllers

{

    public class FileUploadController : Controller

    {

        private IWebHostEnvironment Environment;

        public FileUploadController(IWebHostEnvironment _environment)


        {


            Environment = _environment;


        }

        public IActionResult Index()

        {

            return View(new FileUpload());

        }

        [HttpPost]

        public IActionResult Index(FileUpload obj)

        {

            var uniqueFileName = GetUniqueFileName(obj.FormFile.FileName);

            var uploads = Path.Combine(Environment.WebRootPath, "uploads");

            var filePath = Path.Combine(uploads, uniqueFileName);

            obj.FormFile.CopyTo(new FileStream(filePath, FileMode.Create));

            ViewBag.data = uniqueFileName;

            return View("showfile");

        }

        private string GetUniqueFileName(string fileName)

        {

            fileName = Path.GetFileName(fileName);

            return Path.GetFileNameWithoutExtension(fileName)

                      + "_"

                      + Guid.NewGuid().ToString().Substring(0, 4)

                      + Path.GetExtension(fileName);

        }

    }

}

4)  Create Fileupload View file and Write following code

Code of index.cshtml

@model CodeFirstExample.Models.FileUpload
@{
    ViewData["Title"] = "Index";
}

<form enctype="multipart/form-data" method="post">
    <dl>
        <dt>
            <label asp-for="FormFile"></label>
        </dt>
        <dd>
            <input asp-for="FormFile" type="file" multiple>
            
        </dd>
    </dl>
    <input asp-page-handler="Upload" class="btn" type="submit" value="Upload" />
</form>


5)   Code of showfile.cshtml

@model CodeFirstExample.Models.FileUpload
@{
    ViewData["Title"] = "Index";
}

<form enctype="multipart/form-data" method="post">
    <dl>
        <dt>
            <label asp-for="FormFile"></label>
        </dt>
        <dd>
            <input asp-for="FormFile" type="file" multiple>
            
        </dd>
    </dl>
    <input asp-page-handler="Upload" class="btn" type="submit" value="Upload" />
</form>



Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)