Saturday, 30 May 2015

ASP.NET MVC Image and document Upload functionaltiy

My Model Along with validations
==================================================================
 (1)Model Class

public partial class PersonInformation
    {
     
        public byte[] Image { get; set; }
        public byte[] Resume { get; set; }
     
        [Required(ErrorMessage = "Please Upload image")]
        [ValidateFile]
        public HttpPostedFileBase file { get; set; }

        [Required(ErrorMessage="Please upload resume")]
        [ValidateMsFile]
        public HttpPostedFileBase resumeFile { get; set; }
       
    }
(2) Validations for image file

    public class ValidateFileAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            int MaxContentLength = 1024 * 1024 * 3; //3 MB
            string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };

            var file = value as HttpPostedFileBase;

            if (file == null)
                return true;
            else if          (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
            {
                ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ", AllowedFileExtensions);
                return false;
            }
            else if (file.ContentLength > MaxContentLength)
            {
                ErrorMessage = "Your Photo is too large, maximum allowed size is : " +                    (MaxContentLength / 1024).ToString() + "MB";
                return false;
            }
            else
                return true;
        }
    }
(3)Validations for document

    public class ValidateMsFileAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            int MaxContentLength = 1024 * 1024 * 3; //3 MB
            string[] AllowedFileExtensions = new string[] { ".docx", ".doc", ".xls", ".xlsx" };

            var file = value as HttpPostedFileBase;

            if (file == null)
                return true;
            else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
            {
                ErrorMessage = "Please upload Your resume of type: " + string.Join(", ", AllowedFileExtensions);
                return false;
            }
            else if (file.ContentLength > MaxContentLength)
            {
                ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
                return false;
            }
            else
                return true;
        }
    }

My controller
========================================================================
 [HttpPost]
        public ActionResult Registration(PersonInformation model)
        {
            try
            {

               SampleWorksEntities db = new SampleWorksEntities();
                    var personinfo = new PersonInformation();
                    if (model.file != null && model.resumeFile != null && ModelState.IsValid)
                    {
                        //image
                        var content = new byte[model.file.ContentLength];
                        model.file.InputStream.Read(content, 0, model.file.ContentLength);
                        personinfo.Image = content;
                        personinfo.file = model.file;

                        string destination = Server.MapPath(Path.Combine("~/PersonImages/", Path.GetFileName(model.file.FileName)));
                        model.file.SaveAs(destination);

                        //resume

                        var resumeContent = new byte[model.resumeFile.ContentLength];
                        model.resumeFile.InputStream.Read(resumeContent, 0, model.resumeFile.ContentLength);
                        personinfo.Resume = resumeContent;
                        personinfo.resumeFile = model.resumeFile;

                        string resumePath = Server.MapPath(Path.Combine("~/PersonResume/", Path.GetFileName(model.resumeFile.FileName)));
                        model.resumeFile.SaveAs(resumePath);

                        personinfo.resumePath = resumePath;

                        db.PersonInformations.Add(personinfo);
                        db.SaveChanges();

            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
             
            }
            return RedirectToAction("Registration");
        }
 public ActionResult Registration()
        {
         
            return View();
        }

My View
===================================================================
@model RegistrationDBFirst.PersonInformation
@{
    ViewBag.Title = "Registration";
}

@section Scripts
{
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/jqueryval")
    @Styles.Render("~/Content/jqueryui");
}

@using (Html.BeginForm("Registration", "Registration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <table>
        <tr>
            <td colspan="2">
                <span>Registration page:</span>
            </td>
        </tr>
          <tr>
            <td>
                <span>Select Image :</span>
            </td>
            <td>
              `@Html.TextBoxFor(m => m.file, new { type = "file" })
                 @Html.ValidationMessageFor(m=>m.file)
            </td>
        </tr>
         <tr>
            <td>
                <span>Select Resume :</span>
            </td>
            <td>
              `@Html.TextBoxFor(m=>m.resumeFile,new{ type="file"})
                @Html.ValidationMessageFor(m => m.resumeFile)
            </td>
        </tr>*@
         <tr>
            <td colspan="2">
              <input type="submit" value="Register" />
            </td>
        </tr>
    </table>
}

public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-1.7.1.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-1.8.20.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

     
            bundles.Add(new StyleBundle("~/Content/jqueryui").Include("~/Content/themes/base/jquery-ui.css"));

        }
    }

No comments:

Post a Comment