Wednesday, December 30, 2009

Save Images into Sql Server Database Table using asp.net FileUpload Control

This article will explain how one can insert or save images into a sql server database table using asp.net FileUpload control. You may ask why we will save or store images into sql server database table instead of a server folder? The answer is its easy to use, easy to manage, easy to backup as well as easy programming. But one thing you have to keep in mind that you need to extend the size of your database rather than your regular size. Always deleting images from server folder is a hectic job where security will play a great role but if you store images into sql server database you can remove images or related images by issuing a simple delete sql command.

If you want to upload images into server folder then click here.

If you want to display images from server folder into datalist then click here.

To start to explain how to store images into sql server database  or Upload images into sql server first create a below like table:




















Where ID is the identity field which you will use as a foreign key when entering details data like products_images. In products_images you can easily use imageid as a thumbnail image or large image. The table columns for products_images may like ProductID, ImageType & ImageID.

Now add a webpage in your project and named it Save_Images.aspx then copy the HTML Markup code from below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Save_Images.aspx.cs" Inherits="Save_Images" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>How to save images into sql server database</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        Name:        
        <asp:TextBox runat="server" ID="txt_Image_Name"></asp:TextBox><br />    
        Image Path:
        <asp:FileUpload runat="server" ID="FileUpload1" /><br /><br />
        <asp:Button runat="server" ID="cmd_Upload" Text="Upload Image" OnClick="cmd_Upload_Click" />

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

Your page will look like below:













Now under cmd_Upload button write the below server side code. For your better understanding i have put full code here:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;

public partial class Save_Images : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void cmd_Upload_Click(object sender, EventArgs e)
    {
        string s_Image_Name = txt_Image_Name.Text.ToString();
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
        {
            byte[] n_Image_Size = new byte [FileUpload1.PostedFile.ContentLength];
            HttpPostedFile Posted_Image = FileUpload1.PostedFile;
            Posted_Image.InputStream.Read(n_Image_Size, 0, (int)FileUpload1.PostedFile.ContentLength);

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO Images(Name,[Content],Size,Type)" +
                              " VALUES (@Image_Name,@Image_Content,@Image_Size,@Image_Type)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;

            SqlParameter Image_Name = new SqlParameter("@Image_Name", SqlDbType.VarChar, 500);
            Image_Name.Value = txt_Image_Name.Text;
            cmd.Parameters.Add(Image_Name);

            SqlParameter Image_Content = new SqlParameter("@Image_Content", SqlDbType.Image, n_Image_Size.Length);
            Image_Content.Value = n_Image_Size;
            cmd.Parameters.Add(Image_Content);

            SqlParameter Image_Size = new SqlParameter("@Image_Size", SqlDbType.BigInt, 99999);
            Image_Size.Value = FileUpload1.PostedFile.ContentLength;
            cmd.Parameters.Add(Image_Size);

            SqlParameter Image_Type = new SqlParameter("@Image_Type", SqlDbType.VarChar, 500);
            Image_Type.Value = FileUpload1.PostedFile.ContentType;
            cmd.Parameters.Add(Image_Type);


            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
}
Now run your page give a name for your image. Then select an image to upload. For multiple upload you may read my another post CLICK HERE. Click on upload. Hope your image will be successfully uploaded. Go to the SqlServer andopen the images table. You will get a scenario like below:






So now i hope you can upload images into your sql server using FileUpload Asp.net control. In my next article i will show you how one can retrieve images from Sql Server into a GridView/DataList/Repeater control.

5 comments:

salman ansari said...

nice article..thax a lot...but i want this with jquery and want use my web method in place of aspx page..can u help me out from it

Unika Infocom said...

It's Help full...

Unika Infocom said...

Good Website...

Anonymous said...

veryyyyyyyyyyyy helpfull

Debasmita said...

Thank u

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash