How to upload image using HTML fileupload in c#

In this article, we will learn how to upload the image without using fileupload control so in this article we used HTML control.
We will set the enctype attribute of the form to multipart/form-data; then you can access the uploaded file using the HttpRequest.Files collection.
We can also learn for more understanding.

Source Code:-

<form id="form1" runat="server" enctype="multipart/form-data">
 <input type="file" id="fileupload" name="fileupload" />
 <asp:Button runat="server" ID="btnsubmit" OnClick="btnsubmit_Click" Text="Upload Image" />

Code Behind(c#):-

protected void btnsubmit_Click(object sender, EventArgs e)
        HttpPostedFile file = Request.Files["fileupload"];

        //check file was submitted
        if (file != null && file.ContentLength > 0)

            string filename = Path.GetFileName(file.FileName);
            file.SaveAs(Server.MapPath(Path.Combine("~/image/", filename)));

If you want to upload image on page load or without click on button
Source Code:-
<html xmlns="">
<head runat="server">

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

    <form id="form1" runat="server">
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <br />
            <asp:Label ID="lblmsg" runat="server" Text="File uploaded successfully." ForeColor="Green"
                Visible="false" />
            <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" Style="display: none" />


Code Behind(c#):-

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

    protected void Upload(object sender, EventArgs e)
        FileUpload1.SaveAs(Server.MapPath("~/images/" + Path.GetFileName(FileUpload1.FileName)));
        // you can use here datavase also and save the values in database

        lblmsg.Visible = true;

How to upload image using HTML fileupload in c# How to upload image using HTML fileupload in c# Reviewed by NEERAJ SRIVASTAVA on 8:15:00 PM Rating: 5

No comments:

Powered by Blogger.