File Uploads With Parameter in Asp.net Core

Introduction

In this article, we are going to run across how to upload files in asp.internet cadre spider web awarding and store them in root directory of application. We are going to utilize IFormFile to upload files and too run across how to laissez passer other data with the file.

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

In this commodity,

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

What is IFormFile

ASP.NET Cadre has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives the states access to metadata similar ContentDisposition, ContentType, Length, FileName, and more than. IFormFile also provides some methods used to store files. The IFormFile interface likewise allows usa to read the contents of a file via an attainable Stream.

Create Asp.Internet Cadre Projection

Step one

Open Visual Studio and click on create new project.

Step ii

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

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

Step iii

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

  • Projection Proper noun
  • Location where you want to store your projection

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

Step 4

In the adjacent screen, configure other details or go out as default and click on create button.

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

Stride five

Now our project has been created. Now 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 then select MVC Controller – Empty and click on Add push button. Then Enter controller name and click on add button.

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

Pace 6

At present we have to create model in Models folder. Which we are going to use for passing information from view to controller.

Hither nosotros create three model as given below

ResponseModel

This model contains three properties which are IsResponse, IsSuccess, and Message. This model will exist inherited by the other two, and nosotros are using this as response status and message afterward performing some operation.

          public form ReponseModel {     public cord Message { get; fix; }     public bool IsSuccess { get; set; }     public bool IsResponse { become; set; } }        

SingleFileModel

Nosotros volition use this model to upload a single file at a time. This model contains 2 properties, FileName which we will utilize equally filename when storing file on server. And other is File which is blazon of IFormFile. Both backdrop have Information Required Note Attributes for showing validation to user.

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

MultipleFilesModel

We will use this model to shop multiple files at a fourth dimension. This model contains merely one property, which is type of IFormFile listing.

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

Upload Single File

Pace 1

Create view of single file upload. Hither I used alphabetize 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 view, correct 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. So click on Add push button.

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

Step 2

Create design for your view equally per your requirements. Here I employ simple design as you see in below code.

          @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 form="alert alarm-success">                 @Model.Message             </div>         }         else         {             <div class="alert alert-danger">                 @Model.Message             </div>         }     }     <div class="row mt-ii">         <div class="col-12">             <label class="col-form-label">Enter File Name For Salve</label>             <input asp-for="FileName" course="grade-control" />             <span asp-validation-for="FileName" class="text-danger"></span>         </div>     </div>      <div course="row mt-ii">         <div class="col-12">             <characterization class="col-form-label">Select File</label>             <input asp-for="File" form="form-control" />             <span asp-validation-for="File" class="text-danger"></span>         </div>     </div>       <div class="row mt-ii">         <div form="col-12">             <push type="submit" grade="btn btn-success">Upload File</button>         </div>     </div> </course>        

Explanation

  • Every bit you tin come across in the higher up code snippet, I created a form with post methods and redirect to Upload controller and Upload Activity method.
  • Here we are passing form data (files) with other data, so nosotros have added enctype = "multipart/form-data" aspect in form tag.
  • Nosotros also add push button of submit type which submit our grade to given action method.
  • Hither as well used our response model for showing success and error message in alert component of bootstrap, which is respectively success and danger as per IsSuccess property.

Step 3

Create mail method which stores file on server.

          [HttpPost] public IActionResult Upload(SingleFileModel model) {     if (ModelState.IsValid)     {         model.IsResponse = true;          cord path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Files");          //create binder if not exist         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 = true;         model.Message = "File upload successfully";     }     return View("Index", model); }        

Caption

  • As you can see in the above code, we create a mail service method called Upload which accepts SingleFileModel as parameter.
  • And then nosotros are checking if our model is valid or not using ModelState.Valid property. If model is valid so it goes to next operation, otherwise render view and show validation message.
  • Next we are creating a variable called path which contains our root directory path where we are going to store our files.
  • In unmarried file upload, nosotros store a file with the name of use's input, so here we get 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

Step 1

Add together new action methods in controller equally shown in below code. Here we pass MultipleFilesModel in view.

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

Pace ii

Add together design in your view as per your requirements.

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

Explanation

  • As you tin can meet to a higher place, this view is almost the same equally single file upload view. But here we used merely one control which is file upload and too add together multiple attribute in input tag which allow us to select multiple files.
  • Besides, we post form to different method which has logic for uploading multiple files.

Step 3

Create post 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 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); }        

Explanation

  • As you can see in the above code here nosotros created a post method named MultiUpload which takes MultipleFilesModel equally a parameter.
  • Foremost,  we check if ModelState is valid or not.
  • Then we cheque our files property of Listing<IFormFile> has 1 or more files or not.
  • Then iterate all the files using for each loop. In this loop same equally unmarried file upload code we shop file but hither we use name of file itself equally file name instead of user input.
  • After this, return success message in our response model properties and render to MultiFile view.
  • And final, I as well add a menu for these 2 views in layout file. To hands navigate betwixt these two views. You can 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'southward it. This is how we upload and store single or multiple files on server in asp.net core using IFormFile. I hope you lot find this useful and get some assist. Thanks.

You can admission source lawmaking from my GitHub.

quickgimber60.blogspot.com

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

0 Response to "File Uploads With Parameter in Asp.net Core"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel