Create a Directory of Uploaded Files in Asp.net Core

Introduction

In this article, nosotros are going to run into how to upload files in asp.net cadre web application and shop them in root directory of application. Nosotros are going to use IFormFile to upload files and also run into how to pass other information with the file.

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

In this article,

  • What is IFormFile
  • Create Asp.Cyberspace 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 united states of america access to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile also provides some methods used to shop files. The IFormFile interface besides allows the states 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 projection.

Pace two

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

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

Step 3

In next screen, enter the following details and click on Next button.

  • Project Proper noun
  • Location where you lot want to store your project

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

Pace 4

In the side by side screen, configure other details or exit every bit default and click on create push.

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

Footstep 5

At present our projection has been created. At present we will create a 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

Select Controller from left side filter and and so select MVC Controller – Empty and click on Add button. And so Enter controller proper noun and click on add push button.

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

Step 6

Now we have to create model in Models folder. Which we are going to use for passing data from view to controller.

Hither we create three model as given below

ResponseModel

This model contains three properties which are IsResponse, IsSuccess, and Message. This model will be inherited by the other two, and we are using this as response condition and bulletin subsequently performing some functioning.

          public class ReponseModel {     public string Message { get; prepare; }     public bool IsSuccess { get; set; }     public bool IsResponse { go; set; } }        

SingleFileModel

We will apply this model to upload a single file at a time. This model contains two properties, FileName which we will use as filename when storing file on server. And other is File which is type of IFormFile. Both properties accept Data Required Note Attributes for showing validation to user.

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

MultipleFilesModel

We will use this model to store multiple files at a time. This model contains simply i belongings, which is blazon of IFormFile list.

          public class MultipleFilesModel : ReponseModel {    [Required(ErrorMessage = "Delight select files")]     public List<IFormFile> Files { get; set; } }        

Upload Unmarried File

Step one

Create view of single file upload. Here I used alphabetize activeness method for this. From index, nosotros are passing our model SingleFileModel to view for accessing its properties on view side.

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

To add together view, right click on action method and click on add view.

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

And then select View from left side filter and select Razor View – Empty. And then click on Add push.

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

Step 2

Create pattern for your view as per your requirements. Here I employ unproblematic design as y'all come across in beneath lawmaking.

          @model UploadFile.Models.SingleFileModel  @{     ViewData["Title"] = "Single File Upload";  } <form asp-action="Upload" asp-controller="Upload" method="post" enctype = "multipart/form-information">     @if (Model.IsResponse)     {         if (Model.IsSuccess)         {             <div class="alert alert-success">                 @Model.Bulletin             </div>         }         else         {             <div course="alarm alert-danger">                 @Model.Message             </div>         }     }     <div class="row mt-ii">         <div course="col-12">             <label grade="col-form-label">Enter File Name For Salvage</label>             <input asp-for="FileName" course="grade-control" />             <span asp-validation-for="FileName" class="text-danger"></span>         </div>     </div>      <div class="row mt-two">         <div class="col-12">             <label course="col-form-label">Select File</label>             <input asp-for="File" course="form-control" />             <span asp-validation-for="File" class="text-danger"></bridge>         </div>     </div>       <div class="row mt-two">         <div class="col-12">             <button type="submit" course="btn btn-success">Upload File</button>         </div>     </div> </form>        

Explanation

  • Every bit you can see in the in a higher place code snippet, I created a form with mail methods and redirect to Upload controller and Upload Activity method.
  • Here we are passing form information (files) with other data, so we have added enctype = "multipart/grade-data" aspect in class tag.
  • We also add button of submit type which submit our form to given activeness method.
  • Here also used our response model for showing success and fault message in alert component of bootstrap, which is respectively success and danger as per IsSuccess holding.

Step 3

Create post method which stores 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 be         if (!Directory.Exists(path))             Directory.CreateDirectory(path);          //become 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 = truthful;         model.Bulletin = "File upload successfully";     }     render View("Alphabetize", model); }        

Explanation

  • As you lot can see in the above code, we create a postal service method called Upload which accepts SingleFileModel as parameter.
  • And so we are checking if our model is valid or non using ModelState.Valid property. If model is valid then it goes to next operation, otherwise return view and bear witness validation bulletin.
  • Next nosotros are creating a variable chosen path which contains our root directory path where we are going to store our files.
  • In unmarried file upload, we shop a file with the name of utilize's input, so hither nosotros get extension of file using file info and create new file name.
  • So we create a steam for file cosmos and copy incoming file to it using copy method of IFormFile and pass success bulletin to the view.

Output (Showing Validation)

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

Output (Success Bulletin after File Uploaded)

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

Output (File In Server Directory)

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

Upload Multiple Files

Step ane

Add new action methods in controller as shown in below lawmaking. Here nosotros laissez passer MultipleFilesModel in view.

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

Step 2

Add together blueprint in your view equally per your requirements.

          @model UploadFile.Models.MultipleFilesModel  @{     ViewData["Championship"] = "Multi File Upload";  } <form asp-action="MultiUpload" asp-controller="Upload" method="post" enctype="multipart/form-data">     @if (Model.IsResponse)     {         if (Model.IsSuccess)         {             <div class="alarm warning-success">                 @Model.Message             </div>         }         else         {             <div course="alert alert-danger">                 @Model.Message             </div>         }     }      <div class="row mt-2">         <div class="col-12">             <characterization class="col-form-characterization">Select Multiple Files</label>             <input asp-for="Files" grade="form-control" multiple/>             <span asp-validation-for="Files" form="text-danger"></bridge>         </div>     </div>       <div course="row mt-ii">         <div class="col-12">             <button type="submit" class="btn btn-success">Upload Files</button>         </div>     </div> </form>        

Explanation

  • As you can see above, this view is almost the aforementioned equally single file upload view. Only hither we used only 1 command which is file upload and also add multiple aspect in input tag which allow us to select multiple files.
  • Also, we mail course to different method which has logic for uploading multiple files.

Step iii

Create post activeness method on controller side to store multiple files at once.

          [HttpPost] public IActionResult MultiUpload(MultipleFilesModel model) {     if (ModelState.IsValid)     {         model.IsResponse = true;         if (model.Files.Count > 0)         {             foreach (var file in model.Files)             {                  cord path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Files");                  //create folder if non be                 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 = truthful;             model.Bulletin = "Files upload successfully";         }         else         {             model.IsSuccess = fake;             model.Message = "Please select files";         }     }     return View("MultiFile", model); }        

Explanation

  • As you can see in the in a higher place code here we created a post method named MultiUpload which takes MultipleFilesModel equally a parameter.
  • Foremost,  we check if ModelState is valid or not.
  • Then we bank check our files property of List<IFormFile> has ane or more files or non.
  • And so iterate all the files using for each loop. In this loop same as single file upload code we store file simply here we use proper name of file itself as file proper noun instead of user input.
  • After this, return success message in our response model properties and render to MultiFile view.
  • And concluding, I also add a menu for these 2 views in layout file. To easily navigate between these two views. You can exercise as per your requirement.

Output (Showing Validation)

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

Output (Select Files)

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

Output (Files In Server Directory)

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

Conclusion

That'southward it. This is how we upload and shop single or multiple files on server in asp.net core using IFormFile. I hope you find this useful and become some help. Thanks.

You can access source code from my GitHub.

durrmardst.blogspot.com

Source: https://www.c-sharpcorner.com/article/upload-single-or-multiple-files-in-asp-net-core-using-iformfile2/

0 Response to "Create a Directory of Uploaded Files in Asp.net Core"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel