how to save image in database in asp.net C#

In this article, we will discuss about how to save  image in data base with image path.  

Database:-
Design:-




Script:-
Create Database [CodeSolution]

USE [CodeSolution]
GO

/****** Object:  Table [dbo].[image]    Script Date: 10/11/2015 13:50:20 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[image](
          [id] [int] IDENTITY(1,1) NOT NULL,
          [image_name] [nvarchar](max) NULL,
          [image_path] [nvarchar](max) NULL,
 CONSTRAINT [PK_image] PRIMARY KEY CLUSTERED
(
          [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

 Design







Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="imageupload.aspx.cs" Inherits="imageupload" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <fieldset style="width:250px;">
        <legend>Save Image in Database</legend>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnsave" runat="server" OnClick="btnsave_Click" Text="Submit" />
    </fieldset>
   
    </form>
</body>
</html>


Code behind(C#):-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;

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

    }
    protected void btnsave_Click(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC;Initial Catalog=CodeSolution;Persist Security Info=True;User ID=sa; password=12345678");

        con.Open();
        SqlCommand cmd = new SqlCommand("Insert into image(image_name,image_path) values (@image_name,@image_path)", con);
        if (FileUpload1.HasFile)
        {
            string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
            FileUpload1.SaveAs(Server.MapPath("~/Images/" + filename));
            cmd.Parameters.AddWithValue("@image_name", filename);
            cmd.Parameters.AddWithValue("@image_path", "~/Images/" + filename);

        }
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

Out-Put:-






Note: - Create a folder with name of Images in solution explorer 


how to save image in database in asp.net C# how to save image in database in asp.net C# Reviewed by NEERAJ SRIVASTAVA on 3:36:00 PM Rating: 5

No comments:

Powered by Blogger.