File Upload C# Mvc Compress to Server
Introduction
In this article, we are going to see how to upload files in asp.cyberspace cadre web awarding and shop them in root directory of awarding. Nosotros are going to apply IFormFile to upload files and also see how to laissez passer other data with the file.
In this article,
- What is IFormFile
- Create Asp.Internet Core Project
- Upload Single File
- Upload Multiple Files
What is IFormFile
ASP.Cyberspace Cadre has introduced an IFormFile interface that represents transmitted files in an HTTP asking. The interface gives us admission to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile also provides some methods used to shop files. The IFormFile interface also allows u.s.a. to read the contents of a file via an accessible Stream.
Create Asp.Cyberspace Cadre Projection
Step 1
Open Visual Studio and click on create new project.
Step 2
Select ASP.Net Cadre Web App (MVC) and click on next button.
Step 3
In next screen, enter the following details and click on Next push button.
- Projection Name
- Location where yous desire to store your project
Stride 4
In the next screen, configure other details or get out as default and click on create button.
Step 5
Now our projection has been created. Now nosotros volition create a new controller for our operations.
For adding new controller, right click on Controllers folder and click on Add then Controller.
Select Controller from left side filter and and then select MVC Controller – Empty and click on Add push button. And so Enter controller name and click on add button.
Step 6
At present we have to create model in Models folder. Which nosotros are going to use for passing data from view to controller.
Here we create three model every bit 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 status and message afterward performing some operation.
public class ReponseModel { public string Message { get; set; } public bool IsSuccess { get; ready; } public bool IsResponse { get; prepare; } }
SingleFileModel
Nosotros will employ this model to upload a unmarried 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 blazon of IFormFile. Both properties have Information Required Annotation Attributes for showing validation to user.
public class SingleFileModel : ReponseModel { [Required(ErrorMessage = "Please enter file name")] public cord FileName { get; gear up; } [Required(ErrorMessage = "Delight select file")] public IFormFile File{ become; gear up; } }
MultipleFilesModel
Nosotros volition employ this model to store multiple files at a time. This model contains just one belongings, which is type of IFormFile list.
public class MultipleFilesModel : ReponseModel { [Required(ErrorMessage = "Please select files")] public List<IFormFile> Files { get; set; } }
Upload Unmarried File
Step 1
Create view of single file upload. Here I used alphabetize activity method for this. From index, 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 together view, right click on action method and click on add view.
And then select View from left side filter and select Razor View – Empty. And so click on Add button.
Stride 2
Create design for your view every bit per your requirements. Here I apply unproblematic design as you see in below code.
@model UploadFile.Models.SingleFileModel @{ ViewData["Title"] = "Single File Upload"; } <form asp-action="Upload" asp-controller="Upload" method="postal service" enctype = "multipart/class-data"> @if (Model.IsResponse) { if (Model.IsSuccess) { <div class="alert alert-success"> @Model.Message </div> } else { <div grade="warning warning-danger"> @Model.Bulletin </div> } } <div class="row mt-ii"> <div class="col-12"> <label class="col-grade-label">Enter File Name For Save</label> <input asp-for="FileName" form="form-control" /> <span asp-validation-for="FileName" class="text-danger"></span> </div> </div> <div form="row mt-ii"> <div class="col-12"> <label class="col-course-label">Select File</label> <input asp-for="File" grade="form-control" /> <span asp-validation-for="File" form="text-danger"></bridge> </div> </div> <div class="row mt-two"> <div course="col-12"> <button type="submit" class="btn btn-success">Upload File</push> </div> </div> </form>
Explanation
- As yous can meet in the above code snippet, I created a form with post methods and redirect to Upload controller and Upload Activity method.
- Here we are passing class information (files) with other data, so nosotros have added enctype = "multipart/form-data" attribute in grade tag.
- Nosotros also add push of submit blazon which submit our form to given activeness method.
- Here also used our response model for showing success and error message in alert component of bootstrap, which is respectively success and danger as per IsSuccess holding.
Step iii
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); //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); }
Explanation
- As yous tin can see in the above code, we create a post method called Upload which accepts SingleFileModel as parameter.
- So nosotros are checking if our model is valid or not using ModelState.Valid property. If model is valid then it goes to side by side operation, otherwise return view and show validation message.
- Next nosotros are creating a variable called path which contains our root directory path where we are going to shop our files.
- In unmarried file upload, we store a file with the proper noun of use's input, and then hither we get extension of file using file info and create new file name.
- Then we create a steam for file creation and re-create incoming file to it using re-create method of IFormFile and pass success bulletin to the view.
Output (Showing Validation)
Output (Success Message after File Uploaded)
Output (File In Server Directory)
Upload Multiple Files
Footstep 1
Add together new activity methods in controller as shown in below code. Hither nosotros pass MultipleFilesModel in view.
public IActionResult MultiFile() { MultipleFilesModel model = new MultipleFilesModel(); render View(model); }
Pace two
Add pattern in your view as per your requirements.
@model UploadFile.Models.MultipleFilesModel @{ ViewData["Title"] = "Multi File Upload"; } <form 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="alarm alert-danger"> @Model.Bulletin </div> } } <div class="row mt-two"> <div class="col-12"> <label class="col-form-label">Select Multiple Files</characterization> <input asp-for="Files" form="form-control" multiple/> <bridge 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</push> </div> </div> </course>
Explanation
- As you can see higher up, this view is almost the aforementioned every bit single file upload view. But here nosotros used only 1 control which is file upload and also add multiple attribute in input tag which allow us to select multiple files.
- Likewise, nosotros post form to different method which has logic for uploading multiple files.
Stride 3
Create postal service action method on controller side to shop multiple files at once.
[HttpPost] public IActionResult MultiUpload(MultipleFilesModel model) { if (ModelState.IsValid) { model.IsResponse = truthful; 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.Bulletin = "Please select files"; } } return View("MultiFile", model); }
Explanation
- Every bit you lot can see in the to a higher place lawmaking here we created a postal service method named MultiUpload which takes MultipleFilesModel as a parameter.
- Foremost, nosotros check if ModelState is valid or non.
- And then we check our files property of List<IFormFile> has one or more than files or non.
- Then iterate all the files using for each loop. In this loop same as single file upload code we store file simply hither we utilise name of file itself as file name instead of user input.
- Subsequently this, render success bulletin in our response model properties and render 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)
Output (Select Files)
Output (Files In Server Directory)
Determination
That'due south information technology. This is how we upload and store single or multiple files on server in asp.net cadre using IFormFile. I hope yous notice this useful and get some help. Give thanks You.
You can access source code from my GitHub.
Source: https://www.c-sharpcorner.com/article/upload-single-or-multiple-files-in-asp-net-core-using-iformfile2/
0 Response to "File Upload C# Mvc Compress to Server"
Post a Comment