Skip to main content

IMAGE FILE UPLOAD

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:
01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Save_Images.aspx.cs" Inherits="Save_Images" %>
02   
03 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04   
05 <html xmlns="http://www.w3.org/1999/xhtml" >
06 <head runat="server">
07     <title>How to save images into sql server database</title>
08 </head>
09 <body>
10     <form id="form1" runat="server">
11     <div>
12   
13         Name:        
14         <asp:TextBox runat="server" ID="txt_Image_Name"></asp:TextBox>
15       
16         Image Path:
17         <asp:FileUpload runat="server" ID="FileUpload1" />
18   
19         <asp:Button runat="server" ID="cmd_Upload" Text="Upload Image" OnClick="cmd_Upload_Click" />
20   
21     </div>
22     </form>
23 </body>
24 </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:
01 using System;
02 using System.Data;
03 using System.Configuration;
04 using System.Web;
05 using System.Data.SqlClient;
06   
07 public partial class Save_Images : System.Web.UI.Page
08 {
09     protected void Page_Load(object sender, EventArgs e)
10     {
11   
12     }
13     protected void cmd_Upload_Click(object sender, EventArgs e)
14     {
15         string s_Image_Name = txt_Image_Name.Text.ToString();
16         if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
17         {
18             byte[] n_Image_Size = new byte [FileUpload1.PostedFile.ContentLength];
19             HttpPostedFile Posted_Image = FileUpload1.PostedFile;
20             Posted_Image.InputStream.Read(n_Image_Size, 0, (int)FileUpload1.PostedFile.ContentLength);
21   
22             SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);
23   
24             SqlCommand cmd = new SqlCommand();
25             cmd.CommandText = "INSERT INTO Images(Name,[Content],Size,Type)" +
26                               " VALUES (@Image_Name,@Image_Content,@Image_Size,@Image_Type)";
27             cmd.CommandType = CommandType.Text;
28             cmd.Connection = conn;
29   
30             SqlParameter Image_Name = new SqlParameter("@Image_Name", SqlDbType.VarChar, 500);
31             Image_Name.Value = txt_Image_Name.Text;
32             cmd.Parameters.Add(Image_Name);
33   
34             SqlParameter Image_Content = new SqlParameter("@Image_Content", SqlDbType.Image, n_Image_Size.Length);
35             Image_Content.Value = n_Image_Size;
36             cmd.Parameters.Add(Image_Content);
37   
38             SqlParameter Image_Size = new SqlParameter("@Image_Size", SqlDbType.BigInt, 99999);
39             Image_Size.Value = FileUpload1.PostedFile.ContentLength;
40             cmd.Parameters.Add(Image_Size);
41   
42             SqlParameter Image_Type = new SqlParameter("@Image_Type", SqlDbType.VarChar, 500);
43             Image_Type.Value = FileUpload1.PostedFile.ContentType;
44             cmd.Parameters.Add(Image_Type);
45   
46   
47             conn.Open();
48             cmd.ExecuteNonQuery();
49             conn.Close();
50         }
51     }
52 }
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:



Comments

Popular posts from this blog

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {              border : solid1px#c0c0c0;              background : #f0f0f0;              padding : 0px10px10px10px;              position : absolute;              top : -1000px;       } </ style > Step 3:   Create an aspx page and add a Gridview with another gridview in the last TemplateField. The last templatefield will also contain a lable which will

Nested GridView Example In Asp.Net With Expand Collapse

This example shows how to create Nested GridView In Asp.Net Using C# And VB.NET With Expand Collapse Functionality. I have used JavaScript to Create Expandable Collapsible Effect by displaying Plus Minus image buttons. Customers and Orders Table of Northwind Database are used to populate nested GridViews. Drag and place SqlDataSource from toolbox on aspx page and configure and choose it as datasource from smart tags Go to HTML source of page and add 2 TemplateField in <Columns>, one as first column and one as last column of gridview. Place another grid in last templateField column. Markup of page after adding both templatefields will like as shown below. HTML SOURCE 1: < asp:GridView ID ="gvMaster" runat ="server" 2: AllowPaging ="True" 3: AutoGenerateColumns ="False" 4: DataKeyNames ="CustomerID" 5: DataSour

Add Edit Update Records in GridView using Modal Popup in ASP.Net

Add Edit Update Records in GridView using Modal Popup in ASP.Net In this article, I’ll explain how to Add and Edit records in ASP.Net GridView control using ASP.Net AJAX Control Toolkit Modal Popup Extender. Database For this tutorial, I am using Microsoft’s NorthWind database. You can download it using the following link. Download Northwind Database Connection string Below is the connection string to connect to the database. < connectionStrings >     < add name = " conString "      connectionString = " Data Source=.\SQLExpress;database=Northwind;     Integrated Security=true " /> </ connectionStrings >   HTML Markup Below is the HTML Markup of the page. Below you will notice that I have placed a Script Manager and an ASP.Net Update Panel on the page. Inside the Update Panel I have placed an ASP.Net GridView Control along with a Modal Popup Extender that will be used to Add or Edit the records in the GridView