Tuesday, August 30, 2016

Upload and Save Image in ASP.NET

In this article I will explain how to upload and save an image and then retrieve that
image in ASP.NET.

For uploading FileUpload Control is used and for displaying the image there is an
Image Control.

Below is the code for that :

HTML Code (.aspx) :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        &nbsp;<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
        <asp:Label ID="lblMessage" runat="server" Text="" Font-Bold="true" ForeColor="Green"></asp:Label><br />
        <br />
        <asp:Image ID="Image1" runat="server" Width="250px" Height="250px" />
    </div>
    </form>
</body>
</html>

C# Code (.aspx.cs) :


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class SaveImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {
                string filename = Path.GetFileName(FileUpload1.FileName);
                FileUpload1.SaveAs(Server.MapPath("~/images/") + filename);
                lblMessage.Text = "File has been uploaded successfully!";
                Image1.ImageUrl = Server.MapPath("~/images/") + filename;
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Uploading file failed : " + ex.Message;
            }
        }
    }
}

Output :
















If we want to validate with certain image types like jpg, jpeg, gif, png,etc. we can get the
extension of the file using the code :

Path.GetExtension(FileUpload1.FileName)

One thing to be noted is that there is restriction provided by .NET framework to the size
of the uploaded file which is termed as maxRequestLength. It actually specify the limit
of the input stream buffering threshold which is used to prevent denial of service attacks.
Default value of maxRequestLength is 4096 KB( 4MB).

In case if we want to upload bigger file, we can set the value of maxRequestLength
in web.config. 

For eg. if I want to set it to 15 MB, below is the code of web.config

<system.web>
        <httpRuntime maxRequestLength="15360" ></httpRuntime>
....
</system.web>

No comments:

Post a Comment