I'm trying make a website using asp.net mvc 4 where I can upload multiple image files with some information & save it to only .png format. For some reason, everytime I upload I get an error message of NullReference saying,

Object reference not set to an instance of an object.

Informations are saving accurately in MSSQL database but images are not saving in my mentioned path. Here are my codes,

[HttpPost]
    public ActionResult FlatManager(FlatMgt FlatTable, HttpPostedFileBase[] files)
    {
        if (Session["username"] != null)
        {
            if (ModelState.IsValid)
            {
                var AddFlat = FlatTable.Flats;
                rentdb.FlatInfoes.Add(AddFlat);
                rentdb.SaveChanges();
                foreach (HttpPostedFileBase file in files)    //This line showing the error!
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        int imageCount = 0;
                        string picName = FlatTable.Flats.flatno.ToString()+"-"+imageCount;
                        string picExt = Path.GetExtension(file.FileName);
                        if (picExt == ".jpg" || picExt == ".gif" || picExt == ".jpeg")
                        {
                            picExt = ".png";
                        }
                        string path = System.IO.Path.Combine(Server.MapPath("~/Images/"), picName + picExt);
                        file.SaveAs(path);
                        imageCount++;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            file.InputStream.CopyTo(ms);
                            byte[] array = ms.GetBuffer();
                        }
                    }
                    else
                    {
                        TempData["add_fail"] = "Error! Wrong File Type(s)! Please Try Again.";
                        return RedirectToAction("FlatManager");
                    }
                }
                TempData["add_success"] = "Added Successfully!";
                return RedirectToAction("FlatManager");
            }
            else
            {
                TempData["add_fail"] = "Error! Please Provide Valid Information.";
                return RedirectToAction("FlatManager");
            }
        }
        else
        {
            return RedirectToAction("Login");
        }
    }

I can't find any error in my code and I don't see any way that after uploading it'll return NULL for the images since I'm always selecting multiple images. How can I solve this problem? Will be really thankful if someone response. Thanks.

Related posts

Recent Viewed