如何在单个会话变量中存储和检索多个值

时间:2017-05-30 05:05:18

标签: c# asp.net session dropzone.js

我使用dropzone将多个文件上传到服务器。文件将上传到服务器,文件名将存储在表格中。

我正在尝试在会话中添加文件名。 这里的问题是它不会在单个会话中添加多个文件名

这是我的代码:

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);
}

这里我只能为会话添加单个文件名,而不是多个。

如何在单个会话中存储和维护多个文件名:     context.Session [ “imageNames”]

1 个答案:

答案 0 :(得分:1)

您需要从会话中获取当前列表

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

现在添加新项目。

 lstImageNames.Add(destFileName);

回到会话

 context.Session["imageNames"] = lstImageNames;