How to upload image using HTML fileupload in asp.net c#

In this article, we will learn how to upload the image without using asp.net 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" />
</form>

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="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>
</head>
<body>


    <form id="form1" runat="server">
        <div>
            <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" />
        </div>



    </form>
</body>
</html>

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 asp.net c# How to upload image using HTML fileupload in asp.net c# Reviewed by NEERAJ SRIVASTAVA on 8:15:00 PM Rating: 5

No comments:

Powered by Blogger.