Asp.net Mvc Check File Size Before Upload
Introduction
Many times, we are required to upload a file with strongly-typed View and likewise, apply validation on uploading file using data note validators. In this article, I would like to share how we tin upload a file and validate that file.
Clarification
The upload control in MVC checks the file extension likewise every bit the limitation of file size. This validates the control before mail service dorsum to Server side and shows the warning message to end-user using JavaScript.
Steps To Build This Requirement
Step ane
First, create an MVC Empty Template project named every bit "FileUploadValidation".
Step 2
Then, create a Model class file named "FileUpload1.cs".
Lawmaking Ref
- using System;
- using System.Collections.Generic;
- using Arrangement.Cartoon;
- using Organisation.IO;
- using Arrangement.Linq;
- using Organisation.Spider web;
- namespace FileUploadValidation.Models
- {
- public class FileUpload1
- {
- public string ErrorMessage { become; set; }
- public decimal filesize { get; prepare; }
- public string UploadUserFile(HttpPostedFileBase file)
- {
- effort
- {
- var supportedTypes = new [] { "txt" , "doc" , "docx" , "pdf" , "xls" , "xlsx" };
- var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
- if (!supportedTypes.Contains(fileExt))
- {
- ErrorMessage ="File Extension Is InValid - Only Upload Discussion/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" ;
- render ErrorMessage;
- }
- }
- take hold of (Exception ex)
- {
- ErrorMessage ="Upload Container Should Not Exist Empty or Contact Admin" ;
- return ErrorMessage;
- }
- }
- }
- }
Code Description
I have declared 2 variables with unlike data types.
- public string ErrorMessage { become; set; }
- public decimal filesize { get; set; }
The get-go 1 is used to prove warning message to the end-user if any mistake happens during upload of file by the user.
The second ane is to validate the file size if it exceeds.
- public cord UploadUserFile(HttpPostedFileBase file)
Then, I created one Definition and within, I passed one organization defined course object called "HttpPostedFileBase". Information technology serves every bit the base of operations course for classes that provide access to individual files uploaded past client.
And so, I mentioned some supported extensions. You can add any extension. If you want pdf file validation, then add pdf/dr./docx/xls/xlsx/txt/jpg/jpeg/png in variable supported Types.
- var supportedTypes = new [] { "jpg" , "jpeg" , "png" };
- var supportedTypes = new [] { "txt" , "dr." , "docx" , "pdf" , "xls" , "xlsx" };
First, validate the image extensions like "jpg, jpeg, png" merely. 2nd, validate the file extensions like "txt, doc, docx, pdf, xls,xlsx"
- var fileExt = Arrangement.IO.Path.GetExtension(file.FileName).Substring(1);
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 arrangement.
- if (!supportedTypes.Contains(fileExt))
- {
- ErrorMessage ="File Extension Is InValid - Simply Upload WORD/PDF/EXCEL/TXT File" ;
- return ErrorMessage;
- }
Hither ,whatever file is uploaded by the user, it tin be checked every bit valid or not by this code.
- if (!supportedTypes.Contains(fileExt))
If information technology satisfies, information technology is ok else the mistake message will be shown to the end-user.
- ErrorMessage = "File Extension Is InValid - Merely Upload WORD/PDF/EXCEL/TXT File" ;
- render ErrorMessage;
Nosotros will check for file size validation.
- else if (file.ContentLength > (filesize * 1024))
- {
- ErrorMessage ="File size Should Exist UpTo " + filesize + "KB" ;
- return ErrorMessage;
- }
Hither, the file.ContentLength gets the length of the file size in bytes.
So, the filesize * 1024 is the required file size.
If file.ContentLength > filesize * 1024 value will exceed, then the warning message will exist generated.
- ErrorMessage = "File size Should Be UpTo " + filesize + "KB" ;
The filesize value divers in controller class file.
If all conditions are satisfied without any warning messages, so the successful message will come up.
- else
- {
- ErrorMessage ="File Is Successfully Uploaded" ;
- return ErrorMessage;
- }
All to a higher place description of code in Try {} cake.
If any other warning and validation fail then the take hold of block volition show warning message. Like empty upload control and required extension file'due south size more boilerplate.
- catch (Exception ex)
- {
- ErrorMessage ="Upload Container Should Non Be Empty or Contact Admin" ;
- return ErrorMessage;
- }
Step 3
Then, create a Controller class file named "FileController.cs".
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Spider web;
- using System.Web.Mvc;
- using FileUploadValidation.Models;
- using Organisation.Web.UI.WebControls;
- namespace FileUploadValidation.Controllers
- {
- public form FileController : Controller
- {
- public ActionResult Alphabetize()
- {
- 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 != zip )
- {
- ViewBag.ResultErrorMessage = fs.ErrorMessage;
- }
- return View();
- }
- }
- }
Lawmaking Description
Here, I used the reference of Model course file for hereafter one.
- using FileUploadValidation.Models;
Hither, I used Controller action method named "fileupload".Ane for [HttpGet] and another for [HttpPost] attributes.
- [HttpGet]
- public ActionResult fileupload()
- {
- return View();
- }
- [HttpPost]
- public ActionResult fileupload(HttpPostedFileBase file)
- {
- FileUpload1 fs =new FileUpload1();
- fs.filesize = 550;
- string the states = fs.UploadUserFile(file);
- if (united states != cipher )
- {
- ViewBag.ResultErrorMessage = fs.ErrorMessage;
- }
- return View();
- }
Here, I passed the class as earlier discussed on model class.
- public ActionResult fileupload(HttpPostedFileBase file)
Here, I utilise the model class file object to inherits the backdrop.
- FileUpload1 fs = new FileUpload1();
Hither, I mentioned the limit of file size .
- fs.filesize = 550;
That is 550 KB .
Here, I used the Model course part by passing base class object.
- string the states = fs.UploadUserFile(file);
If the uploaded value is not empty or null, then all warnings and successful letters will come up in other ways in all validation letters as defined in model grade file.
- if (us != null )
- {
- ViewBag.ResultErrorMessage = fs.ErrorMessage;
- }
Hither, fault bulletin variable value is assigned to viewbag type that will laissez passer value from controller to view using @ symbol.
Step4
And so, create i View named "fileupload.cshtml" within "~\Views\File\fileupload.cshtml" .
Code Ref
- @model FileUploadValidation.Models.FileUpload1
- @{
- ViewBag.Title ="Satyaprakash File Upload" ;
- }
- <h2 way="background-color: Yellow;color: Blueish; text-marshal: center; font-style: oblique" >SATYA'S WORD/PDF/EXCEL/TXT UPLOAD FILE VALIDATION</h2>
- <fieldset>
- <legend manner="font-family:Arial Black;colour:bluish" >Upload Here</fable>
- <form action="" method= "mail service" enctype= "multipart/course-information" >
- @if (ViewBag.ResultErrorMessage != goose egg )
- {
- <script blazon="text/javascript" >
- window.onload =function () {
- alert("@ViewBag.ResultErrorMessage" );
- };
- </script>
- }
- <input type="file" name= "file" id= "file " />
- <div>
- <input type="submit" value= "Upload" />
- </div>
- </form>
- </fieldset>
- <footer>
- <p style="background-color: Yellow; color: Bluish; text-marshal: heart; font-style: oblique" >© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@
- </footer>
Lawmaking Description
Here, I used model class file reference to access properties , bulletin and function validation through base of operations class object.
- @model FileUploadValidation.Models.FileUpload1
Here, I mentioned title text.
- @{
- ViewBag.Title ="Satyaprakash File Upload" ;
- }
The heading text is mentioned hither.
- <h2 manner= "groundwork-color: Yellow;color: Blue; text-marshal: centre; font-fashion: oblique" >SATYA'S Discussion/PDF/EXCEL/TXT UPLOAD FILE VALIDATION</h2>
Then, I used viewbag validation messages using javascript as defined before in controller form file.
- <form activity= "" method= "post" enctype= "multipart/grade-data" >
- @if (ViewBag.ResultErrorMessage != null )
- {
- <script blazon="text/javascript" >
- window.onload =part () {
- alarm("@ViewBag.ResultErrorMessage" );
- };
- </script>
- }
- <input type="file" proper name= "file" id= "file " />
- <div>
- <input blazon="submit" value= "Upload" />
- </div>
- </form>
The upload control is defined here.
- <input blazon= "file" name= "file" id= "file " />
The push button controller used for postal service back to server and bank check validation of uploaded file by the end user.
- <div>
- <input blazon="submit" value= "Upload" />
- </div>
Here, I used the footer text .
- <footer>
- <p mode="background-colour: Yellow; color: Blue; text-marshal: center; font-way: oblique" >© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@
- </footer>
Step5
Then, nosotros manually configure settings for MVC url routing.
Code Ref
- using Arrangement;
- using System.Collections.Generic;
- using Arrangement.Linq;
- using Organisation.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
- namespace FileUploadValidation
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}" );
- routes.MapRoute(
- proper noun:"Default" ,
- url:"{controller}/{activity}/{id}" ,
- defaults:new { controller = "File" , action = "fileupload" , id = UrlParameter.Optional }
- );
- }
- }
- }
Code Description
Here, I mentioned my Controller proper name and Controller action method name to configure settings for MVC url routing.
defaults: new { controller = "File", action = "fileupload", id=UrlParameter.Optional }
OUTPUT
The Url route of this MVC app is:
http://localhost:62152/File/fileupload
The App View Design looks like this.
Hither no file is uploaded And then, The Message will come similar this.
Here I uploaded ane epitome file , The invalid file extension message volition come.
I uploaded 1 txt file with out whatever error.
I uploaded 1 Excel file with out any mistake.
I uploaded one Discussion file with out whatever error.
I uploaded 1 Pdf file with out whatever mistake.
I uploaded one valid file extension but beyond the size limits.
The footer text style shows the date and time.
Summary
- Create valid file or supported file extensions only for upload and cease 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 "Asp.net Mvc Check File Size Before Upload"
Post a Comment