简体   繁体   中英

how to store and retrieve multiple values inside single session variable

i am using dropzone to upload multiple files to the server. files will be uploaded to server while file names will be stored in table.

i am trying to add file names in session. the problem here is that it doesn't add multiple file names inside single session

here is my code :

string imageSessList = context.Session["imageNames"].ToString();  //if i put this line at the begining, then the debugger doesn't even moves to foreach block


    foreach (string s in context.Request.Files)
    {
        HttpPostedFile file = context.Request.Files[s];
        string fileName = file.FileName;
        string fileExtension = file.ContentType;
        string strUploadFileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
        string strAllowedFileTypes = "***jpg***jpeg***png***gif***bmp***"; //allowed file types
        string destFileName = "";
        List<string> lstImageNames = new List<string>();




        // else upload file
        if (!string.IsNullOrEmpty(fileName))
        {
            if (strAllowedFileTypes.IndexOf("***" + strUploadFileExtension + "***") != -1) //check extension
            {
                if (context.Request.Files[0].ContentLength < 5 * 1024 * 1024) //check filesize
                {
                    // generate file name
                    destFileName = Guid.NewGuid().ToString() + "." + strUploadFileExtension;
                    string destFilePath = HttpContext.Current.Server.MapPath("/resourceContent/") + destFileName;
                    //Save image names to session
                    lstImageNames.Add(destFileName);
                    context.Session["imageNames"] = lstImageNames;
                    file.SaveAs(destFilePath);

                    strMessage = "Success " + destFileName;
                }
                else
                {
                    strMessage = "File Size can't be more than 5 MB.";
                }
            }
            else
            {
                strMessage = "File type not supported!";
            }
        }
    } // foreach
context.Response.Write(strMessage);
}

here i am able to add only single filename to session, not multiple.

how to store and maintain multiple file names in single session : context.Session["imageNames"]

you need to get current list from session

 List<string> lstImageNames= (List<string>)Session["imageNames"];
 if(lstImageNames==null)
     lstImageNames = new List<string>(); // create new list in the first time

now add new item to it.

 lstImageNames.Add(destFileName);

set back to session

 context.Session["imageNames"] = lstImageNames;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM