Asp.net Core Take Each File in a Form and Upload

Introduction

In this article, we are going to encounter how to upload files in asp.internet core spider web application and store them in root directory of awarding. We are going to use IFormFile to upload files and also see how to laissez passer 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 Cadre Project
  • Upload Unmarried File
  • Upload Multiple Files

What is IFormFile

ASP.Internet Core has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives u.s.a. admission to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile likewise provides some methods used to store files. The IFormFile interface likewise allows us to read the contents of a file via an accessible Stream.

Create Asp.Net Core Project

Footstep 1

Open Visual Studio and click on create new projection.

Step 2

Select ASP.Net Cadre Web App (MVC) and click on next push.

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

Footstep 3

In next screen, enter the post-obit details and click on Side by side button.

  • Project Proper name
  • Location where y'all desire to store your project

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

Step four

In the next screen, configure other details or leave as default and click on create push button.

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

Pace 5

Now our project has been created. Now nosotros will create a new controller for our operations.

For calculation new controller, right click on Controllers folder and click on Add together so Controller.

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

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

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

Pace 6

Now nosotros 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 3 backdrop which are IsResponse, IsSuccess, and Bulletin. This model will be inherited by the other two, and nosotros are using this every bit response status and message later on performing some performance.

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

SingleFileModel

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

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

MultipleFilesModel

Nosotros will use this model to store multiple files at a time. This model contains only one property, which is type of IFormFile list.

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

Upload Unmarried File

Step i

Create view of single file upload. Hither I used index action method for this. From index, we are passing our model SingleFileModel to view for accessing its properties on view side.

          public IActionResult Index() {     SingleFileModel model = new SingleFileModel();     render 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

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

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

Step 2

Create design for your view every bit per your requirements. Here I utilize uncomplicated design as you come across in below code.

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

Caption

  • As you lot can run into in the to a higher place lawmaking snippet, I created a course with postal service methods and redirect to Upload controller and Upload Action method.
  • Hither we are passing form data (files) with other data, and then we accept added enctype = "multipart/form-data" attribute in course tag.
  • We too add button of submit type which submit our form to given action method.
  • Hither as well used our response model for showing success and fault message in alert component of bootstrap, which is respectively success and danger as per IsSuccess property.

Stride iii

Create post method which stores file on server.

          [HttpPost] public IActionResult Upload(SingleFileModel model) {     if (ModelState.IsValid)     {         model.IsResponse = truthful;          cord 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);         cord 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.Bulletin = "File upload successfully";     }     return View("Index", model); }        

Explanation

  • As y'all tin see in the above lawmaking, we create a mail method chosen Upload which accepts SingleFileModel every bit parameter.
  • And then we are checking if our model is valid or not using ModelState.Valid property. If model is valid then information technology goes to next operation, otherwise return view and show validation message.
  • Side by side we are creating a variable chosen path which contains our root directory path where we are going to shop our files.
  • In single file upload, we store a file with the proper noun of apply's input, and so here we go extension of file using file info and create new file name.
  • Then we create a steam for file creation and copy incoming file to it 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

Output (Success Message 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

Footstep one

Add together new activity methods in controller as shown in below code. Here nosotros laissez passer MultipleFilesModel in view.

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

Footstep 2

Add blueprint in your view as per your requirements.

          @model UploadFile.Models.MultipleFilesModel  @{     ViewData["Title"] = "Multi File Upload";  } <grade asp-activeness="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 course="col-12">             <label class="col-class-label">Select Multiple Files</label>             <input asp-for="Files" course="course-command" multiple/>             <bridge asp-validation-for="Files" class="text-danger"></span>         </div>     </div>       <div class="row mt-ii">         <div grade="col-12">             <push button type="submit" class="btn btn-success">Upload Files</push>         </div>     </div> </form>        

Explanation

  • As you tin can see higher up, this view is almost the same every bit single file upload view. But here we used merely 1 command which is file upload and besides add together multiple attribute in input tag which allow united states of america to select multiple files.
  • Also, we post class to different method which has logic for uploading multiple files.

Step 3

Create mail action 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)             {                  string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Files");                  //create folder if non 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 = faux;             model.Message = "Please select files";         }     }     return View("MultiFile", model); }        

Caption

  • Every bit you can see in the above code here we created a post method named MultiUpload which takes MultipleFilesModel as a parameter.
  • Foremost,  nosotros check if ModelState is valid or not.
  • Then we check our files holding of List<IFormFile> has one or more files or not.
  • Then iterate all the files using for each loop. In this loop same every bit single file upload code nosotros store file but here nosotros utilise proper name of file itself as file name instead of user input.
  • After this, render success message in our response model properties and return to MultiFile view.
  • And last, I also add together a menu for these two views in layout file. To easily navigate between these two views. Yous tin do 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's information technology. 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 assist. Thank You.

You tin admission source code from my GitHub.

johnstonfainterep.blogspot.com

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

0 Response to "Asp.net Core Take Each File in a Form and Upload"

Enviar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel