Tuesday, October 4, 2016

Save and retrieve images from database using C# in ASP.NET


  • Create  the interface with a file uploader and an image like this.

  • Create a table to save images.

  • We'll see how to save an image to the database. Add the following html code to the create the interface.

<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">

        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#<%=Image1.ClientID%>').prop('src', e.target.result)
                }
                reader.readAsDataURL(input.files[0]);
                }
            }
            $("#uploadFile").change(function () {
                readURL(this);
            });
    </script>
</head>
<body>
    <form id="form1" runat="server">

        <table>
            <tr>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="Attach Image:" Style="font-weight: 700"></asp:Label>
                </td>
                <td>
                    <asp:FileUpload ID="uploadFile" runat="server" onchange="readURL(this)" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Image ID="Image1" runat="server" Height="100px" Width="100px" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnSave" runat="server" Text="Save" Width="75px" ValidationGroup="Save" OnClick="btnSave_Click" />
                </td>
                <td>
                    <asp:Button ID="btnRetrive" runat="server" Text="Retrive" OnClick="btnRetrive_Click" />
                </td>
            </tr>
        </table>
    </form>

</body>


  • After attaching an image, it shows the preview in the image control.

The image saving code is as follows.

protected void btnSave_Click(object sender, EventArgs e)
{
    int imageId = 1;//Table's first row - default image
    if (uploadFile.PostedFile.FileName != string.Empty)
    {
        imageId = imageUpload();
    }
    Image1.ImageUrl = "Image.aspx?ImageID=" + imageId + "";
}

private int imageUpload()
{
    string filePath = uploadFile.PostedFile.FileName;
    int imageId = 1;
    string filename = Path.GetFileName(filePath);

    string ext = Path.GetExtension(filename);
    ext = ext.ToLower();
    string contenttype = String.Empty;

    switch (ext)
    {
        case ".jpg":
            contenttype = "image/jpg";
            break;
        case ".png":
            contenttype = "image/png";
            break;
        case ".gif":
            contenttype = "image/gif";
            break;
        default:
            break;
    }
    if (contenttype != String.Empty)
    {
        Stream fs = uploadFile.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        byte[] bytes = br.ReadBytes((Int32)fs.Length);

        imageId = page6Service.UpdateImage(filename, contenttype, bytes);
    }
    return imageId;
}
  • We can retrieve a particular saved image with the following code

protected void btnRetrive_Click(object sender, EventArgs e)
{
       Image1.ImageUrl = "Image.aspx?ImageID=1";
}


  • To retrieve an image like this, first we have to create a web page as Image.aspx with an empty form. In the Page_Load event of that page add this code.

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["ImageID"] != null)
    {
        try
        {
            DataTable dt = page6Service.retrieveImage(Convert.ToInt32(Request.QueryString["ImageID"]));
            if (dt.Rows.Count > 0)
            {
                byte[] bytes = (byte[])dt.Rows[0]["Data"];
                Response.Buffer = true;
                Response.Charset = "";
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.ContentType = dt.Rows[0]["ContentType"].ToString();
                Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

No comments:

Post a Comment