Subitted file handling technique in server-side ASP.NET (along with other data) in Non-AJAX way


//--> Non-ajax way --------------------------------
  //HTML
          <form method="post" action="~/Admin/Content/SubmitFile" enctype="multipart/form-data">
                <select name="course" id="course">...</select>
                <input type="text" name="lesson" id="lesson" />
                <input type="file" name="myfile" />
                <input type="submit" value="submit" />
          </form>
  
  //Server-side
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult SubmitFile(FormCollection data)
        {
             String lessonName = data["lessonName"].ToString();
             
            //--> Option-A
              var fileName = Request.Files["filea"].FileName.ToString();
              var fileExtension = Path.GetExtension(fileName);
              var mainSavingDirectory = HttpContext.Server.MapPath("~/Photos");
              string fileSavingPath = Path.Combine(mainSavingDirectory, "Content", "Video", fileName);
              var file = Request.Files["myfile"];
              file.SaveAs(fileSavingPath);
            //<-- Option-A   
            
            //--> Option-B
              Byte[] submittedFile;
              if (Request.Files["myfile"] != null)
              {
                String fileName = "AnyName.ext";
                var mainSavingDirectory = HttpContext.Server.MapPath("~/Photos");
                string fileSavingPath = Path.Combine(mainSavingDirectory, "Content", "Video", fileName);
 
                using (var binaryReader = new BinaryReader(Request.Files["myfile"].InputStream))
                {
                    submittedFile = binaryReader.ReadBytes(Request.Files["myfile"].ContentLength);
                }
                FileStream fs = new FileStream(fileSavingPath, FileMode.CreateNew);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(submittedFile);
                bw.Close();
              }
        }
//<-- Non-ajax way --------------------------------

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s