Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Thursday, 23 July 2015

Introduction:

In this article I will explain how upload file without clicking submit button. This can be possible by using JavaScript code.

Steps to follow:
1.      Add File Upload Control, label control and Button Control.
2.      Now Hide Label Control and set display none for Button Control.
3.      Now Write Javascript code to Trigger Submit button Click Event, which cause Postback and upload file.
4.     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>

Full Source Code for sample application:

<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">
         <fieldset style="width:320px"><legend><strong> Upload File Without Clicking Submit button</strong></legend>
    <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";
    }

}

0 comments:

Post a Comment