Pages

Wednesday, 25 July 2012

How to keep track of selected file during a postback.


When you select a file and then do a postback, you will lose your selected file. This is because there is no ViewState for posted file in asp.net FileUpload control. This example is to demonstrate an idea of how to save the file in any-postback and if there is a selected file, then we save the file and show the fileName in a hyperlink to download or view,
Example:
<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (this.fuFile.HasFile)
            {                
                string filePath = Server.MapPath(string.Format("~/Uploads/{0}"this.fuFile.FileName));
                if (!System.IO.File.Exists(filePath))
                {
                    this.fuFile.SaveAs(filePath);
                    this.linkSelectedFile.NavigateUrl = this.ResolveUrl(string.Format("~/Uploads/{0}"this.fuFile.FileName));
                    this.linkSelectedFile.Text = this.fuFile.FileName;
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        Select a File: <asp:FileUpload runat="server" ID="fuFile" />
        <asp:HyperLink runat="server" ID="linkSelectedFile" />
        <hr />
        <asp:DropDownList runat="server" ID="ddlItems" AutoPostBack="true">
            <asp:ListItem>Item One</asp:ListItem>
            <asp:ListItem>Item Two</asp:ListItem>
        </asp:DropDownList>
    </form>
</body>
</html>

No comments:

Post a Comment