In this article I will explain how to clear ASP.Net FileUpload control jQuery. ASP.Net FileUpload control is actually HTML Input File element which is ReadOnly i.e. one cannot modify its value on Client Side using jQuery.
Hence I have created a clone of the original control and replaced it with new one in order to clear ASP.Net FileUpload control on Client Side using jQuery.
Clear ASP.Net File Upload control using jQuery
The following HTML Markup consists of an ASP.Net FileUpload control and two Buttons, one for Uploading the File while other for clearing the FileUpload control using jQuery.
When the Clear Button is clicked, it triggers jQuery Button Click event handler assigned to it which first references the FileUpload control and then stores its Id and Name attribute values into two variables.
Then a new dynamic HTML FileUpload is created and attached next to the original FileUpload control and the original FileUpload control is removed from the page.
Finally the Id and the Name attributes of the original FileUpload control are applied to the new FileUpload control.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=btnClear]").click(function () {
//Reference the FileUpload and get its Id and Name.
var fileUpload = $("[id*=FileUpload1]");
var id = fileUpload.attr("id");
var name = fileUpload.attr("name");
//Create a new FileUpload element.
var newFileUpload = $("<input type = 'file' />");
//Append it next to the original FileUpload.
fileUpload.after(newFileUpload);
//Remove the original FileUpload.
fileUpload.remove();
//Set the Id and Name to the new FileUpload.
newFileUpload.attr("id", id);
newFileUpload.attr("name", name);
return false;
});
});
</script>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button Text="Upload" runat="server" OnClick="Upload" />
<asp:Button ID="btnClear" Text="Clear" runat="server" />
Server Side Test
When the Upload Button is clicked the following event handler is executed which displays the name of the Uploaded File.
protected void Upload(object sender, EventArgs e)
{
string fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + fileName + "');", true);
}
Screenshot
Demo
Downloads