In this article I will explain with an example, how to upload file without clicking Submit Button when using the FileUpload control in ASP.Net using C# and VB.Net.
The Submit Button will be hidden and as soon as File is selected using FileUpload control, the Submit Button click event is triggered using JavaScript which will do PostBack and file is uploaded.
HTML Markup
The following HTML Markup consists of an ASP.Net FileUpload control, a Label and a Button which is hidden using CSS.
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Label ID="lblMessage" runat="server" Text="File uploaded successfully." ForeColor="Green"
Visible="false" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" Style="display: none" />
Namespaces
You will need to import the following namespace.
C#
VB.Net
Upload File without clicking Submit Button using FileUpload control in ASP.Net
Inside the Page Load event of the page, the JavaScript OnChange event handler of the ASP.Net FileUpload control is set to call the UploadFile JavaScript function.
C#
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes["onchange"] = "UploadFile(this)";
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
FileUpload1.Attributes("onchange") = "UploadFile(this)"
End Sub
The UploadFile JavaScript function will be executed when a File is selected using the ASP.Net FileUpload control. It will first check whether the FileUpload has selected file and then it will trigger the click event of the Submit Button.
<script type="text/javascript">
function UploadFile(fileUpload) {
if (fileUpload.value != '') {
document.getElementById("<%=btnUpload.ClientID %>").click();
}
}
</script>
Saving the Uploaded file
The following event handler saves the uploaded file to a folder and displays the success message using Label control.
C#
protected void Upload(object sender, EventArgs e)
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + Path.GetFileName(FileUpload1.FileName)));
lblMessage.Visible = true;
}
VB.Net
Protected Sub Upload(sender As Object, e As EventArgs)
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + Path.GetFileName(FileUpload1.FileName)))
lblMessage.Visible = True
End Sub
Screenshot
Browser Compatibility
The
above code has been tested in the following browsers.
* All
browser logos displayed above are property of their respective owners.
Downloads