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".

ASP.NET
Step 2

Then, create a Model class file named "FileUpload1.cs".

Lawmaking Ref

  1. using System;
  2. using System.Collections.Generic;
  3. using Arrangement.Cartoon;
  4. using Organisation.IO;
  5. using Arrangement.Linq;
  6. using Organisation.Spider web;
  7. namespace FileUploadValidation.Models
  8. {
  9. public class  FileUpload1
  10.     {
  11. public  string ErrorMessage { become; set; }
  12. public  decimal filesize { get; prepare; }
  13. public  string UploadUserFile(HttpPostedFileBase file)
  14.         {
  15. effort
  16.             {
  17. var  supportedTypes = new [] { "txt" , "doc" , "docx" , "pdf" , "xls" , "xlsx"  };
  18. var  fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
  19. if  (!supportedTypes.Contains(fileExt))
  20.                 {
  21.                     ErrorMessage ="File Extension Is InValid - Only Upload Discussion/PDF/EXCEL/TXT File" ;
  22. return  ErrorMessage;
  23.                 }
  24. else if  (file.ContentLength > (filesize * 1024))
  25.                 {
  26.                     ErrorMessage ="File size Should Be UpTo "  + filesize + "KB" ;
  27. return  ErrorMessage;
  28.                 }
  29. else
  30.                 {
  31.                     ErrorMessage ="File Is Successfully Uploaded" ;
  32. render  ErrorMessage;
  33.                 }
  34.             }
  35. take hold of  (Exception ex)
  36.             {
  37.                 ErrorMessage ="Upload Container Should Not Exist Empty or Contact Admin" ;
  38. return  ErrorMessage;
  39.             }
  40.         }
  41.     }
  42. }

Code Description

I have declared 2 variables with unlike data types.

  1. public  string ErrorMessage { become; set; }
  2. 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.

  1. 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.

  1. var  supportedTypes = new [] { "jpg" , "jpeg" , "png"  };
  2. 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"

  1. 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.

  1. if  (!supportedTypes.Contains(fileExt))
  2. {
  3.     ErrorMessage ="File Extension Is InValid - Simply Upload WORD/PDF/EXCEL/TXT File" ;
  4.     return  ErrorMessage;
  5. }

Hither ,whatever file is uploaded by the user, it tin be checked every bit valid or not by this code.

  1. if  (!supportedTypes.Contains(fileExt))

If information technology satisfies, information technology is ok else the mistake message will be shown to the end-user.

  1. ErrorMessage = "File Extension Is InValid - Merely Upload WORD/PDF/EXCEL/TXT File" ;
  2. render  ErrorMessage;

Nosotros will check for file size validation.

  1. else if  (file.ContentLength > (filesize * 1024))
  2. {
  3.     ErrorMessage ="File size Should Exist UpTo "  + filesize + "KB" ;
  4. return  ErrorMessage;
  5. }

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.

  1. 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.

  1. else
  2. {
  3.     ErrorMessage ="File Is Successfully Uploaded" ;
  4. return  ErrorMessage;
  5. }

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.

  1. catch  (Exception ex)
  2. {
  3.     ErrorMessage ="Upload Container Should Non Be Empty or Contact Admin" ;
  4.     return  ErrorMessage;
  5. }

ASP.NET

Step 3

Then, create a Controller class file named "FileController.cs".

Code Ref

  1. using  System;
  2. using  System.Collections.Generic;
  3. using  System.Linq;
  4. using  System.Spider web;
  5. using  System.Web.Mvc;
  6. using  FileUploadValidation.Models;
  7. using  Organisation.Web.UI.WebControls;
  8. namespace  FileUploadValidation.Controllers
  9. {
  10. public form  FileController : Controller
  11.     {
  12. public  ActionResult Alphabetize()
  13.         {
  14. return  View();
  15.         }
  16. public  ActionResult fileupload()
  17.         {
  18. return  View();
  19.         }
  20.         [HttpPost]
  21. public  ActionResult fileupload(HttpPostedFileBase file)
  22.         {
  23.             FileUpload1 fs =new  FileUpload1();
  24.             fs.filesize = 550;
  25. cord  us = fs.UploadUserFile(file);
  26. if  (us != zip )
  27.             {
  28.                 ViewBag.ResultErrorMessage = fs.ErrorMessage;
  29.             }
  30. return  View();
  31.         }
  32.     }
  33. }

Lawmaking Description

Here, I used the reference of Model course file for hereafter one.

  1. using  FileUploadValidation.Models;

Hither, I used Controller action method named "fileupload".Ane for [HttpGet] and another for [HttpPost] attributes.

  1. [HttpGet]
  2. public  ActionResult fileupload()
  3. {
  4. return  View();
  5. }
  6. [HttpPost]
  7. public  ActionResult fileupload(HttpPostedFileBase file)
  8. {
  9.     FileUpload1 fs =new  FileUpload1();
  10.     fs.filesize = 550;
  11.     string the states = fs.UploadUserFile(file);
  12. if  (united states != cipher )
  13.     {
  14.         ViewBag.ResultErrorMessage = fs.ErrorMessage;
  15.     }
  16. return  View();
  17. }

Here, I passed the class as earlier discussed on model class.

  1. public  ActionResult fileupload(HttpPostedFileBase file)

Here, I utilise the model class file object to inherits the backdrop.

  1. FileUpload1 fs = new  FileUpload1();

Hither, I mentioned the limit of file size .

  1. fs.filesize = 550;

That is 550 KB .

Here, I used the Model course part by passing base class object.

  1. 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.

  1. if  (us != null )
  2. {
  3.     ViewBag.ResultErrorMessage = fs.ErrorMessage;
  4. }

Hither, fault bulletin variable value is assigned to viewbag type that will laissez passer value from controller to view using @ symbol.

ASP.NET

Step4

And so, create i View named "fileupload.cshtml" within "~\Views\File\fileupload.cshtml" .

Code Ref

  1. @model FileUploadValidation.Models.FileUpload1
  2. @{
  3.     ViewBag.Title ="Satyaprakash File Upload" ;
  4. }
  5. <h2 way="background-color: Yellow;color: Blueish; text-marshal: center; font-style: oblique" >SATYA'S WORD/PDF/EXCEL/TXT UPLOAD FILE VALIDATION</h2>
  6. <fieldset>
  7.     <legend manner="font-family:Arial Black;colour:bluish" >Upload Here</fable>
  8.     <form action=""  method= "mail service"  enctype= "multipart/course-information" >
  9.         @if  (ViewBag.ResultErrorMessage != goose egg )
  10.         {
  11.             <script blazon="text/javascript" >
  12.     window.onload =function  () {
  13.         alert("@ViewBag.ResultErrorMessage" );
  14.        };
  15.             </script>
  16.         }
  17.         <input type="file"  name= "file"  id= "file "  />
  18.         <div>
  19.             <input type="submit"  value= "Upload"  />
  20.         </div>
  21.     </form>
  22. </fieldset>
  23. <footer>
  24.     <p style="background-color: Yellow; color: Bluish; text-marshal: heart; font-style: oblique" >© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@
  25. </footer>

Lawmaking Description

Here, I used model class file reference to access properties , bulletin and function validation through base of operations class object.

  1. @model FileUploadValidation.Models.FileUpload1

Here, I mentioned title text.

  1. @{
  2.     ViewBag.Title ="Satyaprakash File Upload" ;
  3. }

The heading text is mentioned hither.

  1. <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.

  1. <form activity= ""  method= "post"  enctype= "multipart/grade-data" >
  2.         @if  (ViewBag.ResultErrorMessage != null )
  3.         {
  4.             <script blazon="text/javascript" >
  5.     window.onload =part  () {
  6.         alarm("@ViewBag.ResultErrorMessage" );
  7.        };
  8.             </script>
  9.         }
  10.         <input type="file"  proper name= "file"  id= "file "  />
  11.         <div>
  12.             <input blazon="submit"  value= "Upload"  />
  13.         </div>
  14.     </form>

The upload control is defined here.

  1. <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.

  1.  <div>
  2.   <input blazon="submit"  value= "Upload"  />
  3. </div>

Here, I used the footer text .

  1. <footer>
  2.     <p mode="background-colour: Yellow; color: Blue; text-marshal: center; font-way: oblique" >© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@
  3. </footer>

ASP.NET

Step5

Then, nosotros manually configure settings for MVC url routing.

Code Ref

  1. using  Arrangement;
  2. using  System.Collections.Generic;
  3. using  Arrangement.Linq;
  4. using  Organisation.Web;
  5. using  System.Web.Mvc;
  6. using  System.Web.Routing;
  7. namespace  FileUploadValidation
  8. {
  9. public class  RouteConfig
  10.     {
  11. public static void  RegisterRoutes(RouteCollection routes)
  12.         {
  13.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}" );
  14.             routes.MapRoute(
  15.                 proper noun:"Default" ,
  16.                 url:"{controller}/{activity}/{id}" ,
  17.                 defaults:new  { controller = "File" , action = "fileupload" , id = UrlParameter.Optional }
  18.             );
  19.         }
  20.     }
  21. }

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 }

ASP.NET

OUTPUT

The Url route of this MVC app is:

http://localhost:62152/File/fileupload

The App View Design looks like this.

ASP.NET

Hither no file is uploaded And then, The Message will come similar this.

ASP.NET

Here I uploaded ane epitome file , The invalid file extension message volition come.

ASP.NET

ASP.NET

I uploaded 1 txt file with out whatever error.

ASP.NET

I uploaded 1 Excel file with out any mistake.

ASP.NET

I uploaded one Discussion file with out whatever error.

ASP.NET

I uploaded 1 Pdf file with out whatever mistake.

ASP.NET

I uploaded one valid file extension but beyond the size limits.

ASP.NET

The footer text style shows the date and time.

ASP.NET

Summary

  1. Create valid file or supported file extensions only for upload and cease user requirement.
  2. Validation for the valid file extensions.
  3. Validation for the invalid file extensions.

sealalaing87.blogspot.com

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel