How to UploadFile Without button Click in Asp.Net

Description:-

File Upload Controls is nothing but we can Upload File from System to where we want to upload in this Code we will Create without any button Click how we can upload file. When we select file from File Upload Controls then Automatically Uploaded from Server or where we want to upload our file. Here Without button Click we will Call Button Click event When File Upload property Attribute Change then we can Fire Script function and Upload file.

Default.aspx:-

<div style="margin-bottom: 150px; margin-top: 41px; border: 2px solid Green; width: 371px; height: 92px; margin-left: 37px;"> <br />
  <asp:FileUpload ID="FileUpload1" runat="server" Height="22px" />
  <br />
  <br />
  <asp:Label ID="lblMessage" runat="server" Text="File uploaded successfully." ForeColor="Green" Font-Bold="true" Visible="false" />
  <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" Style="display: none" />
</div>

JavaScript:-
Now Create Script for getting File Upload Controls ID and Button ID When we Upload File.

<script type="text/javascript">
   function UploadFile(fileUpload) {
      if (fileUpload.value != '') {
          document.getElementById("<%=btnUpload.ClientID %>").click();
      }
   }
</script>

Default.aspx.cs:-
Now go to Code behind File and Code for File Upload in Server. Here I have Give Simple Example for Upload file in server.

protected void Page_Load(object sender, EventArgs e)
{
  FileUpload1.Attributes["onchange"] = "UploadFile(this)";
}

protected void Upload(object sender, EventArgs e)
{
  FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + Path.GetFileName(FileUpload1.FileName)));
  lblMessage.Visible = true;
}

Output:-

Related Posts

Previous
Next Post »

Thanks for comments.....