Mvc How to Use Validation to Upload Afile
Introduction
Many times, nosotros are required to upload a file with strongly-typed View and likewise, apply validation on uploading file using data annotation validators. In this article, I would like to share how we tin can upload a file and validate that file.
Description
The upload control in MVC checks the file extension as well as the limitation of file size. This validates the control earlier post back to Server side and shows the warning message to end-user using JavaScript.
Steps To Build This Requirement
Step 1
First, create an MVC Empty Template project named as "FileUploadValidation".
Pace 2
And then, create a Model class file named "FileUpload1.cs".
Code Ref
- using System;
- using System.Collections.Generic;
- using Organization.Drawing;
- using Organization.IO;
- using System.Linq;
- using Arrangement.Web;
- namespace FileUploadValidation.Models
- {
- public grade FileUpload1
- {
- public string ErrorMessage { get; set; }
- public decimal filesize { become; set; }
- public string UploadUserFile(HttpPostedFileBase file)
- {
- endeavor
- {
- var supportedTypes = new [] { "txt" , "physician" , "docx" , "pdf" , "xls" , "xlsx" };
- var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(one);
- if (!supportedTypes.Contains(fileExt))
- {
- ErrorMessage ="File Extension Is InValid - Simply Upload WORD/PDF/EXCEL/TXT File" ;
- return ErrorMessage;
- }
- else if (file.ContentLength > (filesize * 1024))
- {
- ErrorMessage ="File size Should Be UpTo " + filesize + "KB" ;
- return ErrorMessage;
- }
- else
- {
- ErrorMessage ="File Is Successfully Uploaded" ;
- return ErrorMessage;
- }
- }
- catch (Exception ex)
- {
- ErrorMessage ="Upload Container Should Not Be Empty or Contact Admin" ;
- render ErrorMessage;
- }
- }
- }
- }
Code Description
I have alleged two variables with different data types.
- public string ErrorMessage { become; fix; }
- public decimal filesize { get; set; }
The first one is used to show alarm bulletin to the end-user if whatsoever fault happens during upload of file past the user.
The second one is to validate the file size if it exceeds.
- public string UploadUserFile(HttpPostedFileBase file)
Then, I created i Definition and inside, I passed i system defined grade object called "HttpPostedFileBase". It serves as the base of operations course for classes that provide access to individual files uploaded by client.
And so, I mentioned some supported extensions. You can add any extension. If you want pdf file validation, then add pdf/physician/docx/xls/xlsx/txt/jpg/jpeg/png in variable supported Types.
- var supportedTypes = new [] { "jpg" , "jpeg" , "png" };
- var supportedTypes = new [] { "txt" , "doc" , "docx" , "pdf" , "xls" , "xlsx" };
Outset, validate the image extensions like "jpg, jpeg, png" only. 2d, validate the file extensions like "txt, doc, docx, pdf, xls,xlsx"
- var fileExt = Organisation.IO.Path.GetExtension(file.FileName).Substring(i);
This volition fetch the extension of posted file.
Here, GetExtension method is used to get the extension of uploaded file that is file.FileName From the path of the system.
- if (!supportedTypes.Contains(fileExt))
- {
- ErrorMessage ="File Extension Is InValid - But Upload Word/PDF/EXCEL/TXT File" ;
- return ErrorMessage;
- }
Hither ,whatever file is uploaded by the user, it can be checked equally valid or non by this lawmaking.
- if (!supportedTypes.Contains(fileExt))
If information technology satisfies, it is ok else the error bulletin will be shown to the stop-user.
- ErrorMessage = "File Extension Is InValid - But Upload Give-and-take/PDF/EXCEL/TXT File" ;
- render ErrorMessage;
We volition bank check for file size validation.
- else if (file.ContentLength > (filesize * 1024))
- {
- ErrorMessage ="File size Should Be UpTo " + filesize + "KB" ;
- render ErrorMessage;
- }
Hither, the file.ContentLength gets the length of the file size in bytes.
Then, the filesize * 1024 is the required file size.
If file.ContentLength > filesize * 1024 value will exceed, and then the alert bulletin volition be generated.
- ErrorMessage = "File size Should Exist UpTo " + filesize + "KB" ;
The filesize value divers in controller course file.
If all conditions are satisfied without whatsoever alert messages, then the successful message volition come.
- else
- {
- ErrorMessage ="File Is Successfully Uploaded" ;
- return ErrorMessage;
- }
All above description of code in Effort {} cake.
If any other warning and validation fail then the catch block volition show alert message. Like empty upload control and required extension file's size more than boilerplate.
- catch (Exception ex)
- {
- ErrorMessage ="Upload Container Should Non Be Empty or Contact Admin" ;
- return ErrorMessage;
- }
Pace 3
Then, create a Controller grade file named "FileController.cs".
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using Organisation.Web;
- using Organization.Web.Mvc;
- using FileUploadValidation.Models;
- using System.Web.UI.WebControls;
- namespace FileUploadValidation.Controllers
- {
- public class FileController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult fileupload()
- {
- return View();
- }
- [HttpPost]
- public ActionResult fileupload(HttpPostedFileBase file)
- {
- FileUpload1 fs =new FileUpload1();
- fs.filesize = 550;
- cord us = fs.UploadUserFile(file);
- if (us != null )
- {
- ViewBag.ResultErrorMessage = fs.ErrorMessage;
- }
- return View();
- }
- }
- }
Code Description
Here, I used the reference of Model class file for future one.
- using FileUploadValidation.Models;
Here, I used Controller activity method named "fileupload".One for [HttpGet] and some other for [HttpPost] attributes.
- [HttpGet]
- public ActionResult fileupload()
- {
- render View();
- }
- [HttpPost]
- public ActionResult fileupload(HttpPostedFileBase file)
- {
- FileUpload1 fs =new FileUpload1();
- fs.filesize = 550;
- cord united states = fs.UploadUserFile(file);
- if (usa != nada )
- {
- ViewBag.ResultErrorMessage = fs.ErrorMessage;
- }
- return View();
- }
Here, I passed the course equally earlier discussed on model class.
- public ActionResult fileupload(HttpPostedFileBase file)
Here, I use the model class file object to inherits the properties.
- FileUpload1 fs = new FileUpload1();
Here, I mentioned the limit of file size .
- fs.filesize = 550;
That is 550 KB .
Here, I used the Model class function by passing base form object.
- string us = fs.UploadUserFile(file);
If the uploaded value is not empty or zip, then all warnings and successful messages volition come in other ways in all validation messages as divers in model class file.
- if (usa != nada )
- {
- ViewBag.ResultErrorMessage = fs.ErrorMessage;
- }
Here, error message variable value is assigned to viewbag type that will pass value from controller to view using @ symbol.
Step4
Then, create one View named "fileupload.cshtml" inside "~\Views\File\fileupload.cshtml" .
Lawmaking Ref
- @model FileUploadValidation.Models.FileUpload1
- @{
- ViewBag.Title ="Satyaprakash File Upload" ;
- }
- <h2 manner="background-color: Xanthous;color: Blue; text-align: center; font-mode: oblique" >SATYA'Southward Discussion/PDF/EXCEL/TXT UPLOAD FILE VALIDATION</h2>
- <fieldset>
- <fable style="font-family:Arial Black;color:bluish" >Upload Here</legend>
- <form action="" method= "post" enctype= "multipart/form-data" >
- @if (ViewBag.ResultErrorMessage != null )
- {
- <script type="text/javascript" >
- window.onload =office () {
- warning("@ViewBag.ResultErrorMessage" );
- };
- </script>
- }
- <input type="file" proper noun= "file" id= "file " />
- <div>
- <input type="submit" value= "Upload" />
- </div>
- </form>
- </fieldset>
- <footer>
- <p style="groundwork-color: Yellowish; color: Bluish; text-align: center; font-mode: oblique" >© @DateTime.Now.ToLocalTime()</p> @*Add Appointment Fourth dimension*@
- </footer>
Lawmaking Description
Here, I used model class file reference to access properties , message and function validation through base of operations grade object.
- @model FileUploadValidation.Models.FileUpload1
Here, I mentioned title text.
- @{
- ViewBag.Title ="Satyaprakash File Upload" ;
- }
The heading text is mentioned hither.
- <h2 style= "background-color: Xanthous;color: Blueish; text-marshal: center; font-style: oblique" >SATYA'S Give-and-take/PDF/EXCEL/TXT UPLOAD FILE VALIDATION</h2>
Then, I used viewbag validation letters using javascript as defined earlier in controller class file.
- <form action= "" method= "post" enctype= "multipart/form-information" >
- @if (ViewBag.ResultErrorMessage != aught )
- {
- <script type="text/javascript" >
- window.onload =function () {
- alarm("@ViewBag.ResultErrorMessage" );
- };
- </script>
- }
- <input type="file" name= "file" id= "file " />
- <div>
- <input type="submit" value= "Upload" />
- </div>
- </course>
The upload control is defined hither.
- <input type= "file" name= "file" id= "file " />
The button controller used for mail service back to server and check validation of uploaded file by the finish user.
- <div>
- <input type="submit" value= "Upload" />
- </div>
Here, I used the footer text .
- <footer>
- <p style="background-color: Yellow; color: Blue; text-align: center; font-style: oblique" >© @DateTime.At present.ToLocalTime()</p> @*Add Appointment Time*@
- </footer>
Step5
Then, we manually configure settings for MVC url routing.
Code Ref
- using Organization;
- using Organization.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Spider web.Routing;
- namespace FileUploadValidation
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}" );
- routes.MapRoute(
- proper name:"Default" ,
- url:"{controller}/{action}/{id}" ,
- defaults:new { controller = "File" , activeness = "fileupload" , id = UrlParameter.Optional }
- );
- }
- }
- }
Lawmaking Description
Hither, I mentioned my Controller name and Controller activeness method proper name to configure settings for MVC url routing.
defaults: new { controller = "File", action = "fileupload", id=UrlParameter.Optional }
OUTPUT
The Url road of this MVC app is:
http://localhost:62152/File/fileupload
The App View Pattern looks like this.
Hither no file is uploaded And so, The Message will come like this.
Here I uploaded i paradigm file , The invalid file extension message will come.
I uploaded one txt file with out any error.
I uploaded one Excel file with out any fault.
I uploaded one Word file with out whatever error.
I uploaded one Pdf file with out any fault.
I uploaded one valid file extension simply across the size limits.
The footer text style shows the appointment and time.
Summary
- Create valid file or supported file extensions simply for upload and end user requirement.
- Validation for the valid file extensions.
- Validation for the invalid file extensions.
Source: https://www.c-sharpcorner.com/article/file-upload-extension-validation-in-asp-net-mvc-and-javascript/
0 Response to "Mvc How to Use Validation to Upload Afile"
Postar um comentário