ASP.NET上传文件,已经上传的大小保存在session中,在另一个页面中读取session的值不行

想自己做个ASP.NET上传文件时显示进度条的, 按照自己的想法,其实也就是显示每次已经上传的字节,从网上找到一个方法是能够把文件变成流以后再慢慢写入的,我在那个循环写入的时候每循环一次都把已经上传的字节保存在session中,然后在另一个页面我读取该session值,即是已上传的字节,我放在网上测试,上传大点的文件,在浏览器刷新的时候我再打开另一个页面,该页面只是读取session的值,但是我发现如果文件没有上传完的时候另一个读取session的值的页面也同时打不开,难道在写session的时候不能读取session吗?
请教大家,是怎么回事?下面附上代码:
HTML页面,只显示HTML的上传组件:
<form id="form1" name="uploadForm" method="post" enctype="multipart/form-data" action="upload.ashx">
    <input type="file" id="imgFile" name="imgFile" style=" 220px;" />
    <input type="submit" value="上传"/>   
    </form>


upload.ashx上传一般处理程序,负责上传文件,通过流的方式
<%@ WebHandler Language="C#" class="upload" %>



using System;
using System.Web;

public class upload : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        HttpPostedFile imgFile = HttpContext.Current.Request.Files["imgFile"];
        string savePath = context.Server.MapPath("~/uploadfile/niunan/"+imgFile.FileName);


        long totalBytes = imgFile.ContentLength;
        System.IO.Stream st = imgFile.InputStream;
        System.IO.Stream so = new System.IO.FileStream(savePath, System.IO.FileMode.Create);
        long totalDownloadedByte = 0;  // 已经上传的大小
        byte[] by = new byte[1024];
        int osize = st.Read(by, 0, (int)by.Length);
        while (osize > 0)
        {
            totalDownloadedByte = osize + totalDownloadedByte;
            context.Session["len"] = totalDownloadedByte;  // 存session,表示已经上传了的字节
            so.Write(by, 0, osize);
            osize = st.Read(by, 0, (int)by.Length);
        }
        so.Close();
        st.Close();
       
        context.Response.Write("<br>保存成功!文件名:"+imgFile.FileName+", 总大小: "+totalBytes);
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}


test.aspx页面,只获取session中的值:
    <form id="form1" runat="server">
    <%
        string str = Session["len"] == null ? "没有值" : Session["len"].ToString();
        Response.Write(str);
    %>
    </form>


我在上传一些大文件的时候,趁还没有上传完毕,就在浏览器另开一个窗口运行test.aspx,想直接读取session中的值,即已经上传的字节,但是发现test.aspx打不开,必须得等到文件上传完毕后才能打开的,读取到的时也只是整个文件的大小...

原文地址:https://www.cnblogs.com/yuhanzhong/p/3402180.html