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

ASP.NET
Pace 2

And then, create a Model class file named "FileUpload1.cs".

Code Ref

  1. using System;
  2. using System.Collections.Generic;
  3. using Organization.Drawing;
  4. using Organization.IO;
  5. using System.Linq;
  6. using Arrangement.Web;
  7. namespace FileUploadValidation.Models
  8. {
  9. public grade  FileUpload1
  10.     {
  11. public  string ErrorMessage { get; set; }
  12. public  decimal filesize { become; set; }
  13. public  string UploadUserFile(HttpPostedFileBase file)
  14.         {
  15. endeavor
  16.             {
  17. var  supportedTypes = new [] { "txt" , "physician" , "docx" , "pdf" , "xls" , "xlsx"  };
  18. var  fileExt = System.IO.Path.GetExtension(file.FileName).Substring(one);
  19. if  (!supportedTypes.Contains(fileExt))
  20.                 {
  21.                     ErrorMessage ="File Extension Is InValid - Simply Upload WORD/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. return  ErrorMessage;
  33.                 }
  34.             }
  35. catch  (Exception ex)
  36.             {
  37.                 ErrorMessage ="Upload Container Should Not Be Empty or Contact Admin" ;
  38. render  ErrorMessage;
  39.             }
  40.         }
  41.     }
  42. }

Code Description

I have alleged two variables with different data types.

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

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

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

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

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

Hither ,whatever file is uploaded by the user, it can be checked equally valid or non by this lawmaking.

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

If information technology satisfies, it is ok else the error bulletin will be shown to the stop-user.

  1. ErrorMessage = "File Extension Is InValid - But Upload Give-and-take/PDF/EXCEL/TXT File" ;
  2. render  ErrorMessage;

We volition bank check for file size validation.

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

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.

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

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

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.

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

ASP.NET

Pace 3

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

Code Ref

  1. using  System;
  2. using  System.Collections.Generic;
  3. using  System.Linq;
  4. using  Organisation.Web;
  5. using  Organization.Web.Mvc;
  6. using  FileUploadValidation.Models;
  7. using  System.Web.UI.WebControls;
  8. namespace  FileUploadValidation.Controllers
  9. {
  10. public class  FileController : Controller
  11.     {
  12. public  ActionResult Index()
  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 != null )
  27.             {
  28.                 ViewBag.ResultErrorMessage = fs.ErrorMessage;
  29.             }
  30. return  View();
  31.         }
  32.     }
  33. }

Code Description

Here, I used the reference of Model class file for future one.

  1. using  FileUploadValidation.Models;

Here, I used Controller activity method named "fileupload".One for [HttpGet] and some other for [HttpPost] attributes.

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

Here, I passed the course equally earlier discussed on model class.

  1. public  ActionResult fileupload(HttpPostedFileBase file)

Here, I use the model class file object to inherits the properties.

  1. FileUpload1 fs = new  FileUpload1();

Here, I mentioned the limit of file size .

  1. fs.filesize = 550;

That is 550 KB .

Here, I used the Model class function by passing base form object.

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

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

Here, error message variable value is assigned to viewbag type that will pass value from controller to view using @ symbol.

ASP.NET

Step4

Then, create one View named "fileupload.cshtml" inside "~\Views\File\fileupload.cshtml" .

Lawmaking Ref

  1. @model FileUploadValidation.Models.FileUpload1
  2. @{
  3.     ViewBag.Title ="Satyaprakash File Upload" ;
  4. }
  5. <h2 manner="background-color: Xanthous;color: Blue; text-align: center; font-mode: oblique" >SATYA'Southward Discussion/PDF/EXCEL/TXT UPLOAD FILE VALIDATION</h2>
  6. <fieldset>
  7.     <fable style="font-family:Arial Black;color:bluish" >Upload Here</legend>
  8.     <form action=""  method= "post"  enctype= "multipart/form-data" >
  9.         @if  (ViewBag.ResultErrorMessage != null )
  10.         {
  11.             <script type="text/javascript" >
  12.     window.onload =office  () {
  13.         warning("@ViewBag.ResultErrorMessage" );
  14.        };
  15.             </script>
  16.         }
  17.         <input type="file"  proper noun= "file"  id= "file "  />
  18.         <div>
  19.             <input type="submit"  value= "Upload"  />
  20.         </div>
  21.     </form>
  22. </fieldset>
  23. <footer>
  24.     <p style="groundwork-color: Yellowish; color: Bluish; text-align: center; font-mode: oblique" >© @DateTime.Now.ToLocalTime()</p> @*Add Appointment Fourth dimension*@
  25. </footer>

Lawmaking Description

Here, I used model class file reference to access properties , message and function validation through base of operations grade 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 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.

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

The upload control is defined hither.

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

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

Here, I used the footer text .

  1. <footer>
  2.     <p style="background-color: Yellow; color: Blue; text-align: center; font-style: oblique" >© @DateTime.At present.ToLocalTime()</p> @*Add Appointment Time*@
  3. </footer>

ASP.NET

Step5

Then, we manually configure settings for MVC url routing.

Code Ref

  1. using  Organization;
  2. using  Organization.Collections.Generic;
  3. using  System.Linq;
  4. using  System.Web;
  5. using  System.Web.Mvc;
  6. using  System.Spider 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 name:"Default" ,
  16.                 url:"{controller}/{action}/{id}" ,
  17.                 defaults:new  { controller = "File" , activeness = "fileupload" , id = UrlParameter.Optional }
  18.             );
  19.         }
  20.     }
  21. }

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 }

ASP.NET

OUTPUT

The Url road of this MVC app is:

http://localhost:62152/File/fileupload

The App View Pattern looks like this.

ASP.NET

Hither no file is uploaded And so, The Message will come like this.

ASP.NET

Here I uploaded i paradigm file , The invalid file extension message will come.

ASP.NET

ASP.NET

I uploaded one txt file with out any error.

ASP.NET

I uploaded one Excel file with out any fault.

ASP.NET

I uploaded one Word file with out whatever error.

ASP.NET

I uploaded one Pdf file with out any fault.

ASP.NET

I uploaded one valid file extension simply across the size limits.

ASP.NET

The footer text style shows the appointment and time.

ASP.NET

Summary

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

holguinhagerre.blogspot.com

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel