我创建了一个空ASP。NET应用程序,默认为2页。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:TempMyUpload.bmp");
}
}
}
上传的文件不保存在FileUpload
控件中,控件只有对实际数据所在的响应流的引用。
直到需要时才读取整个响应流,但是如果上传的文件很小,它将被读取到流的缓冲区中。当您执行重定向时,响应流将被关闭,因此缓冲区中未包含的任何内容都无法读取。
你必须将上传的文件保存在它到达的页面中,你不能保存FileUpload
控件以供以后可靠地从中获取文件