Friday 15 October 2021

Save file to server without java script C# ASP.Net

 In this post, you will learn, How to upload an image file to a server without using javascript or jquery. The file will be upload using C#. Unique File name  is generated with datetime string , you implement your logic for the file name. Given code is applicable in both C# MVC and ASP.Net both.

Name Space

using System.IO;


HTML

<form method="post" enctype="multipart/form-data">

      <input type="file" required  id="mainimage" name="mainimage" accept="image/x-png,image/jpeg" /><br />

      <input type="submit" value="Save Image" >

</form>  

C# Code

  [HttpPost]       

       public ActionResult ProjectMainImg()

       {

   if (Request.Files.Count > 0)

               {

                   try

                   {

                       string NewFName=DateTime.Now.Ticks.ToString(),oldfile="";

                       //  Get all files from Request object

                       HttpFileCollectionBase files = Request.Files;

                       for (int i = 0; i <= files.Count - 1; i++)

                       {

                           HttpPostedFileBase file = files[i];

                           string fname = files[0].FileName;

                           string fileName = NewFName;

                           string fileExtension = Path.GetExtension(fname);

                           fname = fileName + fileExtension;

                           // Get the complete folder path and store the file inside it.

                           fname = Path.Combine(Server.MapPath("~/AppImage/project/featureimage/"), fname);

                           file.SaveAs(fname);

                       }

                      

                     

                       return RedirectToAction("ProjectMainImg", "common);

                   }

                   catch (Exception ex)

                   {

                       return RedirectToAction("msg", "common", new { msg = ex.Message  });

                   }

               }

               else

               {

                   return RedirectToAction("msg", "common", new { msg = "No file selected" });

               }          

       }      

     

Next Topic

No comments:

Post a Comment