Thursday, January 16, 2014

How to Upload a file into MVC


Step:-1 Put the Below mention the code as  HTML

  @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
                            new { enctype = "multipart/form-data" }))
          { 
    <label for="file">Upload Image:</label>
    <input type="Myfile" name=" Myfile " id=" Myfile " style="width: 100%;" />
               <input type="submit" name="uploadFile" id="uploadFile"  />
          }


Step 2:- Put below code into your controller
  [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult FileUpload(HttpPostedFileBase uploadFile)
        {
            HttpFileCollection UploadedFile = System.Web.HttpContext.Current.Request.Files;
            
            string path = "~/Upload/";

            for (int i = 0; i < UploadedFile.Count; i++)
            {
                HttpPostedFile filetoUpload = UploadedFile[i];
                if (filetoUpload.ContentLength > 0)
                {
                    string fileName = "";
                    if (Request.Browser.Browser == "IE")
                    {
                        fileName = Path.GetFileName(filetoUpload.FileName);
                    }
                    else
                    {
                        fileName = filetoUpload.FileName;
                    }
                    string fullPathWithFileName = path + fileName;
                    string FilePath = Server.MapPath(fullPathWithFileName);
                    filetoUpload.SaveAs(FilePath);
                }
            }
           
            return View();
        }

1 comment:

  1. Nice demonstration.
    Only one typo mistake.
    Please replace "hpf.FileName" with "filetoUpload.FileName", and also "hpf.SaveAs" with "filetoUpload.SaveAs".

    ReplyDelete