In this article I will explain with an example, how to upload file without clicking Submit Button using FileUpload control in ASP.Net using C# and VB.Net.
HTML Markup
The HTML Markup consists of following controls.
FileUpload – For selecting file.
Label – For displaying success message.
The Label is made hidden by setting Visible property to FALSE.
Button – For uploading selected file.
The Button has been assigned with an OnClick event handler.
The
Button is made hidden as its clicking will be simulated using
JavaScript.
<asp:FileUpload ID="fuUpload"runat="server" />
<br /><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
Uploading File without clicking Submit Button using FileUpload control
Inside the
Page_Load event handler, the FileUpload control has been assigned with an
onchange event handler which calls the
UploadFile JavaScript function.
C#
protected void Page_Load(object sender, EventArgs e)
{
fuUpload.Attributes["onchange"] = "UploadFile(this)";
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
fuUpload.Attributes("onchange") = "UploadFile(this)"
End Sub
Uploading file using JavaScript
UploadFile
The
UploadFile JavaScript function, accepts FileUpload control as a parameter.
Inside the
UploadFile JavaScript function, a check is performed if file is selected or not. If selected 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 file using C# and VB.Net
When the Upload Button is clicked, it saves the uploaded file to a folder.
Finally, the Visible property of a Label control is set to TRUE.
C#
protected void Upload(object sender, EventArgs e)
{
fuUpload.SaveAs(Server.MapPath("~/Uploads/" + Path.GetFileName(fuUpload.FileName)));
lblMessage.Visible = true;
}
VB.Net
Protected Sub Upload(sender As Object, e As EventArgs)
fuUpload.SaveAs(Server.MapPath("~/Uploads/" + Path.GetFileName(fuUpload.FileName)))
lblMessage.Visible = True
End Sub
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads