Friday 6 September 2013

How to use FileUpload Control in Update Panel using Asp.Net

How to use FileUpload Control in Update Panel using Asp.Net

Problem: FileUpload control is not working in update panel in Asp.Net. I will also explain the reason and solution of this problem.

Describe and Reason: The FileUpload control doesn’t work for uploading image using Asynchronous postback when placed in the Update Panel since FileUpload control required full postback to get the image. If you check FileUpload1.HasFile method or FileUpload1.FileName property then it is null. That is because the update panel does not retain the file inside the FileUpoad control.

Solution: So to solve the issue we need to set the Button that is uploading the image to be PostBackTrigger instead of AsyncPostBackTrigger. By doing so the upload button will cause the full post back and get and retain the image in the FileUpload control whenever clicked on.
So set it as:

<Triggers>
<asp:PostBackTrigger ControlID="btnUploadImage" />
</Triggers>

Code for Default.aspx …………………………………………………………………….

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset style="width:250px;">
<legend><b><i>Upload file example in asp.net</i></b></legend>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<table>
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUploadImage" runat="server" Text="Upload"
onclick="btnUploadImage_Click" /><br />
<asp:Image ID="ImageShow" runat="server" Width="150px" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUploadImage" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
</fieldset>
</div>
</form>
</body>
</html>


Code for Default.aspx.cs…………………………………………………………………….

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}

protected void btnUploadImage_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string ImgPath = Server.MapPath("~/Images/" + Guid.NewGuid() + FileUpload1.FileName);
FileUpload1.SaveAs(ImgPath);
string ShowImgPath = ImgPath.Substring(ImgPath.LastIndexOf("\\"));
ImageShow.ImageUrl = "~/Images" + ShowImgPath;
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Please upload Image');", true);
}
}
}

1 comments: