Introduction

In this article we are going to see how to upload files in asp.net core web application and store in root directory of application. Here we are going to use IFormFile for upload files. Here we are also going to see how to pass other data with file.

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in


In this article

  • What is IFormFile
  • Create Asp.Net Core Project
  • Upload Single File
  • Upload Multiple Files

 

What is IFormFile

ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives us access to metadata like ContentDisposition, ContentType, Length, FileName and more. IFormFile also provide some methods which used to store files. The IFormFile interface also allows us to read the contents of a file via an accessible Stream.

 

Create Asp.Net Core Project

Step 1: Open Visual studio and click on create new project.

Step 2: Select ASP.Net Core Web App (MVC) and click on next button.

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in


Step 3: In next screen enter following details and click on Next button.

  • Project Name
  • Location where you want to store your project
  • Solution configuration like create new or use old's and place solution in same folder.
Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in

Step 4: In next screen configure other details or remain same as default and click on create button.
Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in

Step 5: Now our project has been created with default home controller but here we create new controller for our operations.

For adding new controller, right click on Controllers folder and click on Add then Controller.

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in

Select Controller from left side filter and then select MVC Controller – Empty and click on Add button. Then Enter controller name here I enter UploadController.

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in

Step 6: Now we have to create model in Models folder. which we are going to use for passing data from view to controller.

Here we create three model as given below

ResponseModel: This model contain three properties which are IsResponse, IsSuccess and Message.This model will be inherited by other two and we are used this as response status and message after performing some operation.

public class ReponseModel
{
    public string Message { get; set; }
    public bool IsSuccess { get; set; }
    public bool IsResponse { get; set; }
}
C#

SingleFileModel: We will use this model for upload single file at a time. This model contain two properties FileName which we will use as filename when store file on server. And other is File which is type of IFormFile. Both properties have Data Required Annotation Attributes for showing validation to user.

public class SingleFileModel : ReponseModel
{
    [Required(ErrorMessage = "Please enter file name")]
    public string FileName { get; set; }
    [Required(ErrorMessage = "Please select file")]
    public IFormFile File{ get; set; }

}
C#

MultipleFilesModel: We will use this model for store multiple files at a time. This model is contain only one property which is type of IFormFile list.

public class MultipleFilesModel : ReponseModel
{

    [Required(ErrorMessage = "Please select files")]
    public List<IFormFile> Files { get; set; }

}
C#

 

Upload Single File

Step 1: Create view of single file upload. Here I used index action method for this. From index we are passing our model SingleFileModel to view for accessing it’s properties on view side.

public IActionResult Index()
{
    SingleFileModel model = new SingleFileModel();
    return View(model);
}
C#

For add view right click on action method and click on add view.

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in

Then select View from left side of filter and then select Razor View – Empty. Then click on Add button.

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in

Step 2: Now our view is created. Now we have to create design for our view here i use simple design for better understanding.

@model UploadFile.Models.SingleFileModel

@{
    ViewData["Title"] = "Single File Upload";

}
<form asp-action="Upload" asp-controller="Upload" method="post" enctype = "multipart/form-data">
    @if (Model.IsResponse)
    {
        if (Model.IsSuccess)
        {
            <div class="alert alert-success">
                @Model.Message
            </div>
        }
        else
        {
            <div class="alert alert-danger">
                @Model.Message
            </div>
        }
    }
    <div class="row mt-2">
        <div class="col-12">
            <label class="col-form-label">Enter File Name For Save</label>
            <input asp-for="FileName" class="form-control" />
            <span asp-validation-for="FileName" class="text-danger"></span>
        </div>
    </div>

    <div class="row mt-2">
        <div class="col-12">
            <label class="col-form-label">Select File</label>
            <input asp-for="File" class="form-control" />
            <span asp-validation-for="File" class="text-danger"></span>
        </div>
    </div>


    <div class="row mt-2">
        <div class="col-12">
            <button type="submit" class="btn btn-success">Upload File</button>
        </div>
    </div>
</form>
Markup

Explanation

  • As you can see in above code snipped I create a form which is post type and redirect to Upload controller and Upload Action method.
  • Here also add enctype attribute which describe multipart/form-data which required when we are passing file with other data. If you do not pass this attribute you data will be pass to controller but your file will not attached with it.
  • We also add button of submit type which submit our form to given action.
  • On top of view we used our response model for showing success and error message in alert component of bootstrap which is respectively success or danger as per IsSuccess property.

 Step 3: Create post method which store file on server.

[HttpPost]
public IActionResult Upload(SingleFileModel model)
{
    if (ModelState.IsValid)
    {
        model.IsResponse = true;

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

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

        //get file extension
        FileInfo fileInfo = new FileInfo(model.File.FileName);
        string fileName = model.FileName + fileInfo.Extension;

        string fileNameWithPath = Path.Combine(path, fileName);

        using (var stream = new FileStream(fileNameWithPath, FileMode.Create))
        {
            model.File.CopyTo(stream);
        }

        model.IsSuccess = true;
        model.Message = "File upload successfully";

    }
    return View("Index", model);
}
C#

Explanation

  • As you see in above code we create a post method called Upload which has SingleFileModel as parameter.
  • Next we are checking if ModelState is valid or not. We add required attribute in model so if user submit without data then this condition we be false and after returning to index view it’s show error message which we given in attribute.
  • Next we are getting path of our folder in which we are going to store our files. If this folder is not exist then we create.
  • In single file upload we store file with the name of use’s input so here we get extension of file using file info and create new file name.
  • In last save file using copy method of IFormFile and pass success message to the view.

 

Output (Showing Validation)

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in


Output (Success Message after File Uploaded)

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in


Output (File In Server Directory)

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in


Upload Multiple Files

Step 1: Add new methods in controller as shown in below code. Here we pass MultipleFilesModel in view. And Add view for this.

public IActionResult MultiFile()
{
    MultipleFilesModel model = new MultipleFilesModel();
    return View(model);
}
C#

Step 2: Add design in view as given below.

@model UploadFile.Models.MultipleFilesModel

@{
    ViewData["Title"] = "Multi File Upload";

}
<form asp-action="MultiUpload" asp-controller="Upload" method="post" enctype="multipart/form-data">
    @if (Model.IsResponse)
    {
        if (Model.IsSuccess)
        {
            <div class="alert alert-success">
                @Model.Message
            </div>
        }
        else
        {
            <div class="alert alert-danger">
                @Model.Message
            </div>
        }
    }

    <div class="row mt-2">
        <div class="col-12">
            <label class="col-form-label">Select Multiple Files</label>
            <input asp-for="Files" class="form-control" multiple/>
            <span asp-validation-for="Files" class="text-danger"></span>
        </div>
    </div>


    <div class="row mt-2">
        <div class="col-12">
            <button type="submit" class="btn btn-success">Upload Files</button>
        </div>
    </div>
</form>
Markup

Explanation

  • As you shown in above, this view is almost same as above single file upload view. But here we used only one control file upload and also add multiple attribute which allow us to select multiple files.
  • Also we post form to different method which has logic for upload multi files.

Step 3: Create post action method on controller side for store multiple files at ones.

[HttpPost]
public IActionResult MultiUpload(MultipleFilesModel model)
{
    if (ModelState.IsValid)
    {
        model.IsResponse = true;
        if (model.Files.Count > 0)
        {
            foreach (var file in model.Files)
            {

                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, file.FileName);

                using (var stream = new FileStream(fileNameWithPath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

            }
            model.IsSuccess = true;
            model.Message = "Files upload successfully";
        }
        else
        {
            model.IsSuccess = false;
            model.Message = "Please select files";
        }
    }

    return View("MultiFile", model);
}
C#

Explanation

  • As you seen in above code here we create a post method named MultiUpload which take MultipleFilesModel as parameter.
  • First of all here also we check if ModelState is valid or not.
  • Then we check our files property of List<IFormFile> has one or more files or not.
  • Then iterate all the files using foreach loop. In this loop same as single file upload code we store file but here we use name of coming file itself as file name instead of use input.
  • After this return success message in our response model properties and return to MultiFile view which we are created for multi file upload.
  • In last here I also add menu for this two views in layout file. For easily navigate between this two views. You can do as your requirement.

Output (Showing Validation)

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in


Output (Select Files)

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in


Output (Files In Server Directory)

Upload Single Or Multiple Files In ASP.Net Core using IFormFile - YogeshHadiya.in


Conclusion

That’s it. This is how we upload and store single or multiple files on server in asp.net core using IFormFile. I hope you find this useful and get some help. Thank You.

You can access source code from my GitHub.