banner



How To Use Dotnet Core To Upload File

Introduction

In this article, we are going to see how to upload files in asp.net core web application and store them in root directory of application. Nosotros are going to use IFormFile to upload files and also run across how to pass other data with the file.

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

In this article,

  • What is IFormFile
  • Create Asp.Net Cadre 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 access to metadata similar ContentDisposition, ContentType, Length, FileName, and more. IFormFile besides provides some methods used to store files. The IFormFile interface also allows us to read the contents of a file via an attainable Stream.

Create Asp.Net Core Project

Step 1

Open Visual Studio and click on create new project.

Step ii

Select ASP.Internet Cadre Spider web App (MVC) and click on side by side push button.

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

Step 3

In next screen, enter the post-obit details and click on Next push.

  • Project Proper noun
  • Location where yous want to shop your project

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

Step 4

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

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

Pace 5

Now our projection 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 together 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 together button. And then Enter controller name and click on add push.

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

Step six

Now we accept to create model in Models folder. Which nosotros are going to use for passing information from view to controller.

Here we create three model every bit given below

ResponseModel

This model contains three backdrop which are IsResponse, IsSuccess, and Message. This model will exist inherited by the other two, and we are using this equally response status and bulletin after performing some performance.

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

SingleFileModel

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

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

MultipleFilesModel

Nosotros will utilize this model to store multiple files at a time. This model contains merely ane belongings, which is type of IFormFile listing.

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

Upload Single File

Step i

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

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

To add view, right click on activity 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 ii

Create design for your view as per your requirements. Here I apply simple blueprint equally 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/course-data">     @if (Model.IsResponse)     {         if (Model.IsSuccess)         {             <div class="alert alarm-success">                 @Model.Bulletin             </div>         }         else         {             <div class="alert alert-danger">                 @Model.Message             </div>         }     }     <div form="row mt-2">         <div grade="col-12">             <label form="col-grade-characterization">Enter File Name For Save</label>             <input asp-for="FileName" course="course-command" />             <span asp-validation-for="FileName" class="text-danger"></span>         </div>     </div>      <div form="row mt-two">         <div class="col-12">             <label class="col-course-characterization">Select File</characterization>             <input asp-for="File" grade="form-control" />             <span asp-validation-for="File" grade="text-danger"></span>         </div>     </div>       <div class="row mt-ii">         <div class="col-12">             <push blazon="submit" class="btn btn-success">Upload File</button>         </div>     </div> </form>        

Explanation

  • As y'all tin can see in the to a higher place code snippet, I created a course with post methods and redirect to Upload controller and Upload Action method.
  • Here nosotros are passing form data (files) with other information, so we accept added enctype = "multipart/class-data" aspect in class tag.
  • We too add button of submit type which submit our form to given action method.
  • Here as well used our response model for showing success and fault message in warning component of bootstrap, which is respectively success and danger as per IsSuccess property.

Step 3

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

Explanation

  • As yous tin can see in the in a higher place code, we create a post method called Upload which accepts SingleFileModel as parameter.
  • So nosotros are checking if our model is valid or non using ModelState.Valid holding. If model is valid so it goes to next performance, otherwise return view and testify validation message.
  • Side by side we are creating a variable chosen path which contains our root directory path where we are going to store our files.
  • In single file upload, we store a file with the name of apply'south input, so here nosotros become extension of file using file info and create new file proper noun.
  • Then we create a steam for file creation 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 Message afterward 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 new activity methods in controller as shown in below code. Here nosotros pass MultipleFilesModel in view.

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

Step 2

Add design in your view as per your requirements.

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

Caption

  • As you can encounter above, this view is near the same as unmarried file upload view. Merely hither we used only one control which is file upload and also add multiple attribute in input tag which let united states of america to select multiple files.
  • As well, we postal service class to different method which has logic for uploading multiple files.

Pace iii

Create post action method on controller side to store multiple files at in one case.

          [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 binder 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 = imitation;             model.Message = "Please select files";         }     }     return View("MultiFile", model); }        

Explanation

  • As you can come across in the above code hither we created a post method named MultiUpload which takes MultipleFilesModel as a parameter.
  • Foremost,  we check if ModelState is valid or not.
  • Then we bank check our files property of List<IFormFile> has one or more files or not.
  • And then iterate all the files using for each loop. In this loop same as unmarried file upload code we store file but hither we use proper name of file itself as file name instead of user input.
  • Subsequently this, return success message in our response model properties and render to MultiFile view.
  • And last, I as well add a carte for these two views in layout file. To hands navigate between these two views. Yous can do equally 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 it. This is how we upload and shop unmarried or multiple files on server in asp.net cadre using IFormFile. I promise you find this useful and get some help. Thank Yous.

You lot tin can access source code from my GitHub.

How To Use Dotnet Core To Upload File,

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

Posted by: donnersily1998.blogspot.com

0 Response to "How To Use Dotnet Core To Upload File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel