【问题标题】:how to store and retrieve multiple values inside single session variable如何在单个会话变量中存储和检索多个值
【发布时间】:2017-05-30 05:05:17
【问题描述】:

我正在使用 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"]

【问题讨论】:

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


    【解决方案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;
    

    【讨论】:

    • 在读取会话并将其添加到 lstImageNames.Add(destFileName);它不会移动到下一行: context.Session["imageNames"] = lstImageNames;并且进一步不会将值添加到会话中,因此在下一次上传点击时,会话显示为空
    猜你喜欢
    • 2013-08-28
    • 2012-05-31
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多