Tuesday, November 14, 2017

File Upload Control Model MVC C#


TWO File Upload Control in Model With Custom Attribute -Data Annotations


For Understand file upload control in MVC C# (.Net) We are taking example of Upload Profile Pic & Covert Photo. We are defining "HttpPostedFileBase" in Model. Here "FileSize" and "FileTypes" are custom attributes we will create custom attibutes in step2. so don't worry if it's give compile time error.

Step 1 :  Create A Model  


public class FileUploadModel
    {
        [Required(ErrorMessage = "Please Choose Profile Pic")]
        [FileSize(102400)]
        [FileTypes("jpg,jpeg,png")]
        public HttpPostedFileBase ProfilePic { get; set; }

        [Required(ErrorMessage = "Please Choose Cover Photo")]
        [FileSize(1002400)]
        [FileTypes("jpg,jpeg,png")]
        public HttpPostedFileBase CoverPhoto { get; set; }
    }


Step 2 :  Create A Class for  Custom Validation Data Annotation Attribute for Validate Image File.


In above model we have used two custom attribute for validate image size and image type.Validation in MVC can be done using Data Annotations that are applied to both the client and server side, so Create one folder "Attributes" and define below mention class in it.  

Add reference of below class in model defined in step1.


public class FileSizeAttribute : ValidationAttribute
        {
            private readonly int _maxSize;

            public FileSizeAttribute(int maxSize)
            {
                _maxSize = maxSize;
            }

            public override bool IsValid(object value)
            {
                if (value == null) return true;

                return (value as HttpPostedFileBase).ContentLength <= _maxSize;
            }

            public override string FormatErrorMessage(string name)
            {
                return string.Format("The file size should not exceed {0}", _maxSize);
            }
        }


        public class FileTypesAttribute : ValidationAttribute
        {
            private readonly List<string> _types;

            public FileTypesAttribute(string types)
            {
                _types = types.Split(',').ToList();
            }

            public override bool IsValid(object value)
            {
                if (value == null) return true;

                var fileExt = System.IO.Path.GetExtension((value as HttpPostedFileBase).FileName).Substring(1);
                return _types.Contains(fileExt, StringComparer.OrdinalIgnoreCase);
            }

            public override string FormatErrorMessage(string name)
            {
                return string.Format("Invalid file type. Only the following types {0} are supported.", String.Join(", ", _types));
            }
        }


Step 1 :  Create File Upload Controller & View 


We will store profile pic and cover photo in two different directory. 

Controller


public class FileUploadController : Controller
    {
        // GET: FileUpload
        public ActionResult Index()
        {

            return View();
        }

        // HTTP Post Method
        [HttpPost]
        public ActionResult Index(FileUploadModel objfileModel)
        {

            if (ModelState.IsValid)
            {
                if (objfileModel != null && objfileModel.ProfilePic != null && objfileModel.ProfilePic.ContentLength > 0)
                {
                    var ProfilePicName = Path.GetFileName(objfileModel.ProfilePic.FileName);
                    if (!Directory.Exists(Server.MapPath("~\\Uploads\\ProfilePic\\")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~\\Uploads\\ProfilePic\\"));
                    }
                    objfileModel.ProfilePic.SaveAs(Server.MapPath("~\\Uploads\\ProfilePic\\" + ProfilePicName));

                }

                if (objfileModel != null && objfileModel.CoverPhoto != null && objfileModel.CoverPhoto.ContentLength > 0)
                {
                    var CoverPicName = Path.GetFileName(objfileModel.CoverPhoto.FileName);

                    if (!Directory.Exists(Server.MapPath("~\\Uploads\\CoverPhoto\\")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~\\Uploads\\CoverPhoto\\"));
                    }
                    objfileModel.CoverPhoto.SaveAs(Server.MapPath("~\\Uploads\\CoverPhoto\\" + CoverPicName));

                }
                ViewBag.Message = "Upload successfully";
                return RedirectToAction("Index");
            }
            else
            {

                ViewBag.Message = "Error during Upload";
                return View();
                
            }

        }
        
    }


Views


@model  WebApplication1.Models.FileUploadModel
@{
    Layout = null;
}

<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<style>
    .input-validation-error {
        border: 1px solid #ff0000;
        background-color: #e96363;
    }

     .field-validation-error {
        color: #ff0000;
    }

    .field-validation-valid {
        display: none;
    }

    .input-validation-error {
        border: 1px solid ##ff0000;
        background-color: ##FF0000;
    }

    .validation-summary-errors {
        font-weight: bold;
        color: #ff0000;
    }

    .validation-summary-valid {
        display: none;
    }

</style>

<div class="container">
    <h2>File Upload Control Using Strongly Bind Model</h2>
    @using (Html.BeginForm("Index", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <span>@ViewBag.Message</span>
        <form>
            <div class="form-group">
                <span>@Html.LabelFor(m => m.ProfilePic)  &nbsp;</span>
                @Html.TextBoxFor(m => m.ProfilePic, new { type = "file" ,@class="custom-file-input" })
                @Html.ValidationMessageFor(m => m.ProfilePic) <br />
            </div>
            <div class="form-group">
                <span>@Html.LabelFor(m => m.CoverPhoto) &nbsp;</span>
                @Html.TextBoxFor(m => m.CoverPhoto, new { type = "file" })
                @Html.ValidationMessageFor(m => m.CoverPhoto)
            </div>


            <input type="submit" value="Upload" class="btn btn-default" />
        </form>
    }


</div>








No comments:

Post a Comment

Featured Post