0

I want to keep the incoming images in a list as they are loaded visually with Filepond. I'll email them later.but every time a file is called to load it creates the list again.the list is always reset.

 public class HomeController : Controller
    {
        List<HttpPostedFileBase> img = new List<HttpPostedFileBase>();
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Fileupload()
        {
            try
            {
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase file = Request.Files[0];
                    if (file != null && file.ContentLength > 0)
                    {
                        img.Add(file);
                        return Json(true);
                    }
                }
                return Json(false);
            }
            catch
            { return Json(false); }
        }
MultiValidation
  • 823
  • 7
  • 21
  • You have to persist your list of files somewhere. A controller instance is recreated on every request, so after your `FileUpload` returns the lists of files is lost. – MultiValidation Sep 12 '20 at 08:43

1 Answers1

0

It does that because for each HTTP request that you receive on the server if there is a correspondent controller for that the Asp.net framework creates an instance of the controller for you.

In case you want to keep them in the memory in this controller you can declare your list as static.

private static List<HttpPostedFileBase> img = new List<HttpPostedFileBase>();

  • Making a list `static` is not a good solution. This will merge images from all users who has access to the `Fileupload` action. – Rahatur Sep 12 '20 at 08:58
  • I will send data from the form. A contact form. Is it a problem? – Ömer Özdemir Sep 12 '20 at 09:06
  • There is no problem with where you send the data to this controller. I suggest this not to be your final version of the way you implement it. Because you are keeping the data in the ram memory and if the server crashes you lose your images. – Cristian-Ștefăniță Scăueru Sep 12 '20 at 10:19