We can upload file
without clicking submit button using JavaScript or jQuery code in asp.net(c#).
·
Add
File Upload, label and Button asp.net Control.
·
Hide
Label Control and set display none for Button Control.
·
Write
Javascript code to Trigger Submit button Click Event, which cause Postback and
upload file.
·
On
Page load call Javascript function on fileupload control’s “onchange ”
attribute.
JavaScript function
to trigger submit button click event:
<script type="text/javascript">
function UploadFile(fileUpload) {
if (fileUpload.value != '') {
document.getElementById("<%=btnUpload.ClientID %>").click();
}
}
</script>
Sample Code with
HTML code & Code behind:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function UploadFile(fileUpload) {
if (fileUpload.value != '') {
document.getElementById("<%=btnUpload.ClientID %>").click();
}
}
</script>
<style>
.btn {
display:none;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Label ID="Label1" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:Button ID="btnUpload" runat="server" Text="Button" OnClick="Upload" CssClass="btn" /><br /></div></fieldset>
</form>
</body>
</html>
ASP.Net Code in C#:
Add Following Namespace:
using System.IO;
Now Write Following Code:
public partial class FileUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes["onchange"] = "UploadFile(this)";
}
protected void Upload(object sender, EventArgs e)
{
FileUpload1.SaveAs(Server.MapPath("~/Image/" + Path.GetFileName(FileUpload1.FileName)));
Label1.Visible = true;
Label1.Text = "File Uploaded Sucessfully";
}
}