How to upload file in dotnet core mvc

Author : Sachin Sharma
Published On : 10 Apr 2023
Tags: mvc-core

Here I will explain how to upload file in dotnet core mvc.

IFormFile is used for capture transmitted file in http request.IFormFile interface also allows us to read the contents of a file via an accessible Stream.

@model FileUploadModal

    <form>
        <div class="row">
            <div class="col-12">
                <label>Name</label>
                <input type="text" asp-for="Name" class="form-control" />
                <span asp-validation-for="Name"></span>
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-12">
                <label>Upload file</label>
                <input type="file" asp-for="File" class="form-control" />
                <span asp-validation-for="File"></span>
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-12">
                <input type="submit" asp-controller="test" asp-action="fileUpload" class="btn btn-primary" value="Submit" />

            </div>
        </div>
    </form>



public class FileUploadModal
    {        
        [Required]
        public string Name { get; set; }

        [Required]
        public IFormFile File { get; set; }

    }

public class TestController : Controller
    {
        [HttpGet]
        public IActionResult FileUpload()
        {
            return View();
        }

        [HttpPost]
        public IActionResult FileUpload(FileUploadModal req)
        {            

            string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Files");

          //create folder if not exist
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

         
            string fileNameWithPath = Path.Combine(path, req.File.FileName);
            using (var stream = new FileStream(fileNameWithPath, FileMode.Create)){
                 model.File.CopyTo(stream);
             }
            return View();

        }
    }

Comments

No comments have been added to this article.

Add Comment