|
In this article we will explore how to upload file withing the UpdatePanel. When we try to upload file withing UpdatePanel we get HttpPostedFile collection as zero. To upload file within the UpdatePanel we have to work around using iframe.
Let's write some code to achieve this:
Step 1: Create a FileUpload.aspx and place a label to show status, a file upload control and a button. Set the button display style as none to keep it invisible.
<table> <tr> <td> <input type="file" name="attachment" runat="server" id="attachment" /> </td> <td> <asp:Label ID="lblStatus" runat="server"></asp:Label> </td> </tr> <tr> <td> <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" Style="display: none" /> </td> </tr> </table>
Step 2: Place below javascript in the aspx page. uploadFile will fire the click event of the invisible button to upload the file.
< script language="javascript" type="text/javascript"> function uploadFile() { document.getElementById('btnUpload').click(); } </script>
Step 3: Write btnUpload click event handler in the codebehind page.
protected void btnUpload_Click(object sender, EventArgs e) { try { HttpFileCollection uploadFiles = Request.Files; for (int i = 0; i < uploadFiles.Count; i++) { HttpPostedFile uploadFile = uploadFiles[i]; string fileName = Path.GetFileName(uploadFile.FileName); if (fileName.Trim().Length > 0) { uploadFile.SaveAs(Server.MapPath("./Others/") + fileName); lblStatus.Text = "File Uploaded Successfully"; } } } catch (Exception ex) { lblStatus.Text = "Error in uploading file"; } }
Step 4: Create another aspx page, place a updatepanel which will contain IFrame and a button. Load the FileUpload.aspx in the IFrame. uploadFile javascript method in the FileUpload.aspx will be invoked from the btnUpload button of this aspx page.
<asp:UpdatePanel ID="pnlMain" runat="server"> <ContentTemplate> <table> <tr> <td valign="middle"> <iframe id="ifrmUpload" src="FileUpload.aspx" frameborder="0" height="50px" width="260px"> </iframe> </td> <td style="padding-top:0px"> <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClientClick="document.getElementById('ifrmUpload').contentWindow.uploadFile();" /> </td> </tr> </table> </ContentTemplate> </asp:UpdatePanel>
This ends the article of upload file withing upldatepanel.
|