FileUpload通过Session变量超过一定大小并获得“无法访问已关闭的文件”错误

时间:2013-03-06 01:22:33

标签: asp.net

我创建了一个空的ASP.NET应用程序,有2个页面,Default.aspx和Action.aspx(请参见下文)。运行时,我选择一个200k .bmp文件,然后单击保存。然后我得到一个“无法访问已关闭的文件”错误但仅当我的源文件高于55k左右时。是什么赋予了?感谢

Default.aspx的

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="attachmentFileUpload" Width="300px" runat="server" />
    <asp:Button ID="saveButton" runat="server" Text="Save" OnClick="saveButton_Click" />
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class Simple : System.Web.UI.Page
    {
        protected void saveButton_Click(object sender, EventArgs e)
        {
            Session["AttachmentFileUpload"] = attachmentFileUpload;
            Response.Redirect("Action.aspx");
        }
    }
}

Action.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Action.aspx.cs" Inherits="WebApplication1.Action" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

Action.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class Action : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            FileUpload tempFileUpload = (FileUpload)Session["AttachmentFileUpload"];
            tempFileUpload.PostedFile.SaveAs(@"C:\Temp\MyUpload.bmp");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

上传的文件不会保存在FileUpload控件内,控件只会引用实际数据所在的响应流。

在需要之前不会读取整个响应流,但如果上传的文件很小,则会将其读入流的缓冲区。当您进行重定向时,响应流将被关闭,因此无法读取缓冲区中已有的任何内容。

您必须将上传的文件保存在其到达的页面中,您无法保存FileUpload控件以便以后可靠地从中获取文件。