Translate

Tuesday, 21 April 2015

How to upload files in Mvc Application

  File Upload in mvc using C#


In controller you  have to write like below

     
    public ActionResult Fileup()
        {
            Sample smp = new Sample();
            smp.images = Listemp();
            return View(smp);
        }


Add  View to above ActionResult. and the View like below


@using (Html.BeginForm("Fileup", "JqGrid", FormMethod.Post, new { enctype    = "multipart/form-data" }))
{
    <input type="file" name="file" id="fup" />

    <input type="submit" id="btnSubmit" value="submit" />
}



Jquery validations for file upload write it in same view

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

     <script type="text/javascript">
    $(function () {
        $('#btnSubmit').click(function () {
            // alternate
            var fileUpload1 = $("#fup").val();
            var extension1 =      fileUpload1.substring(fileUpload1.lastIndexOf('.'));


            var ValidFileType = ".doc , .pdf , .xls , .xlsx, .docx, .jpeg, .jpg, .png";
            var id = document.getElementById("fup").value;
            if (id.length > 0) {
                var extension = id.substring(id.lastIndexOf('.'));
                var fsize = $("#fup")[0].files[0].size;
                if (ValidFileType.toLowerCase().indexOf(extension) < 0) {
                    alert("Only doc,pdf,jpeg and xls files allowed.");
                    return false;
                }
                else if (parseInt(fsize) > parseInt(1024 * 1024 * 3)) {
                    alert('File size must 3 MB or below.');
                    return false;
                }
            }
            else {
                alert('Please select File.');
                return false;
            }
        });
    });
</script>

 the view show like below




Post method to save selected file 


       [HttpPost]
        public ActionResult Fileup(HttpPostedFileBase file, FormCollection fc)
        {
            Sample smp = new Sample();
            if (file != null && file.ContentLength > 0)
                try
                {
             string path =      Path.Combine(Server.MapPath("~/Images//Upload"),   Path.GetFileName(file.FileName));
                    if (System.IO.File.Exists(path))
                    {
                    }
                    file.SaveAs(path);
                    TempData["Success"] = "File uploaded successfully";
                    smp.images = Listemp();
                }
                catch (Exception ex)
                {
                    TempData["Success"] = "Upload failed";
                }
            return View(smp);
        }





  public List<Sample> Listemp()
        {
            var uploadedFiles = new List<Sample>();
            var files = Directory.GetFiles(Server.MapPath("~/Images/Upload"));
            Sample uploadedFile = null;
            if (files.Count() > 0)
            {

                foreach (var file in files)
                {
                    var fileInfo = new FileInfo(file);
                    uploadedFile = new Sample() { Name = Path.GetFileName(file) };

                    uploadedFile.Path = ("/Images//Upload/") + Path.GetFileName(file);
                    uploadedFile.Size = Convert.ToString((fileInfo.Length) / 1000);
                    uploadedFiles.Add(uploadedFile);
                }
                uploadedFile.images = uploadedFiles;
            }
            return uploadedFile.images;
        }




No comments:

Post a Comment