autoostback时如何在FileUpload控制器中维护文件

本文关键字:控制器 维护 文件 FileUpload autoostback | 更新日期: 2023-09-27 18:08:42

在我的应用程序中,我使用一个Fileupload控制器,一个下拉菜单和一个按钮,这里首先我使用Fileupload控制器选择一个。doc文件,然后我选择下拉菜单值,当我点击按钮时,它检查下拉菜单值是否为> 0

 if (ddlstype.SelectedValue != "0")

如果ddlstype值等于0,则在标签中显示错误消息。这里的下拉菜单有AutoPostBack,代码如下,

<asp:DropDownList ID="ddlstype" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlstype_SelectedIndexChanged" Width="165px"> 

这里我的问题是,如果页面是AutoPostBack,那么文件上传控制变成空,我怎么能在文件上传控制器中维护文件,而AutoPostBack?

autoostback时如何在FileUpload控制器中维护文件

这里在页面加载时在会话中存储文件路径。这样你就不需要使用更新面板

protected void Page_Load(object sender, EventArgs e)
{
    if (this.IsPostBack)
    {
        if (Session["FileUpload1"] == null && Request.Files["FileUpload1"].ContentLength > 0)
        {
            Session["FileUpload1"] = Request.Files["FileUpload1"];
            ImageErrorLabel.Text = Path.GetFileName(Request.Files["FileUpload1"].FileName);
            HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
        }
        else if (Session["FileUpload1"] != null && (Request.Files["FileUpload1"].ContentLength == 0))
        {
            HttpPostedFile file = (HttpPostedFile)Session["FileUpload1"];
            ImageErrorLabel.Text = Path.GetFileName(file.FileName);
        }
        else if (Request.Files["FileUpload1"].ContentLength > 0)
        {
            Session["FileUpload1"] = Request.Files["FileUpload1"];
            ImageErrorLabel.Text = Path.GetFileName(Request.Files["FileUpload1"].FileName);
        }
    }
}

把它放到ddlstype_SelectedIndexChanged

protected void ddlstype_SelectedIndexChanged(object sender, EventArgs e)
{
    HttpPostedFile FileUpload1 = Request.Files["FileUpload1"];
    Session["FileUpload1"] = FileUpload1;
}