selvi jp

selvi jp

  • 1.9k
  • 122
  • 3.7k

i want to upload multiple image and some form data to sql in web api

May 10 2021 12:20 PM
This is my code.Multiple image upload is done but i cant store other data via model.
 
  [HttpPost]
        public HttpResponseMessage Post()
        {
            var httpContext = HttpContext.Current;
          
            string sPath = "";
            sPath = HostingEnvironment.MapPath("~/Images/");
            // Check for any uploaded file  
            if (httpContext.Request.Files.Count > 0)
            {
                //Loop through uploaded files  
                for (int i = 0; i < httpContext.Request.Files.Count; i++)
                {
                    HttpPostedFile hpf = httpContext.Request.Files[i];
                    if (hpf != null)
                    {
                        // Construct file save path  
                        ////var fileSavePath = Path.Combine(HostingEnvironment.MapPath(ConfigurationManager.AppSettings["/Images"]), hpf.FileName);

                        // Save the uploaded file  
                        // SAVE THE FILES IN THE FOLDER.   
                        var fileName = Path.GetFileName(hpf.FileName);
                        var random = Guid.NewGuid() + fileName;
                        hpf.SaveAs(sPath + Path.GetFileName(random));
                       
                        //Insert the File to Database Table.    
                        WebApiDatabaseEntities entities = new WebApiDatabaseEntities();
                        ImageUpload file = new ImageUpload();
                        ImageUpload model = new ImageUpload();
                        file.ImagePath = "Images/" + Path.GetFileName(hpf.FileName);
                        file.ImageName = hpf.FileName;
                        file.ImageType = hpf.ContentType;
                        file.CreatedDate = DateTime.Now;
                        file.CreatedBy = "Selvi";
                        file.Title = model.Title;//here why null value pass
                        entities.ImageUploads.Add(file);
                        entities.SaveChanges();
                    }
                }
            }

            // Return status code  
            return Request.CreateResponse(HttpStatusCode.Created);
        }

Answers (2)