IT Community - Software Programming, Web Development and Technical Support

How to upload an image to DB in ASP.Net?

This is a discussion on How to upload an image to DB in ASP.Net? within the ASP and ASP.NET Programming forums, part of the Web Development category; How to upload an image to DB in ASP.Net?...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > ASP and ASP.NET Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 07-24-2007, 06:18 AM
mobilegeek mobilegeek is offline
D-Web Analyst
 
Join Date: Jun 2007
Posts: 205
mobilegeek is on a distinguished road
Question How to upload an image to DB in ASP.Net?

How to upload an image to DB in ASP.Net?
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 07-24-2007, 06:38 AM
oxygen oxygen is offline
D-Web Architect
 
Join Date: Jun 2007
Posts: 633
oxygen is on a distinguished road
Default Re: How to upload an image to DB in ASP.Net?

Use the following code for uploading image to DB in ASP.Net.

public void UploadBtn_Click(object sender, System.EventArgs e)
{
if(page.IsValid)
{
stream imgStream=UploadFile.PostedFile.InputStream;
int imgLen=UploadFile.PostedFile.ContentLength;
string imgContentType=UploadFile.PostedFile.ContentType;
string imgName=txtImgName.Value;
byte[] imgBinaryData=new byte[imgLen];
int n=imgStream.Read(imgBinaryData,0,imgLen);
int RowsAffected=SaveToDB(imgName, imgBinaryData,
imgContentType);
if(RowsAffected>0)
{
Response.Write(“The Image was saved”);
}
else
{
Response.Write(“An error occurred uploading the image”);
}
}
}

Private int SaveToDB(string imgName, byte[] imgbin, string imgcontenttype)
{
SqlConnection connection=new SqlConnection(ConfigurationSettings.Appsettings[“DSN”]);
SqlCommand command=new SqlCommand(“Insert into image (img_name,img_data,img_contenttype) values (@img_name,@img_data,@img_contenttype)”,connection );
SqlParameter param=new SqlParameter(“@img_name”,SqlDbType.Varchar,50);
param.Value=imgName;
command.Parameters.Add(param);
SqlParameter param1=new SqlParameter(“@img_data”,SqlDbType.Image);
param1.Value =imgbin;
command.Parameters.Add(param1);
SqlParameter param2=new SqlParameter(“@img_contenttype”, SqlDbType.Varchar,50);
param2.Value=imgcontenttype;
command.Parameters.Add(param2);
connection.Open();
int numRowsAffected=command.ExecuteNonQuery();
connection.Close();
return numRowsAffected;
}

Web.Config
<configuration>
<appSettings>
<add key=”DSN” value=”server=localhost;uid=sa;pwd=;Database=aaa”/>
</appSettings>
<system.web>
<customErrors mode=”Off”/>
<system.web>
</configuration>
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 08-06-2007, 07:59 AM
krishnakumar krishnakumar is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 206
krishnakumar is on a distinguished road
Default Re: How to upload an image to DB in ASP.Net?

can we retrieve the image from database using C#?:
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 08-06-2007, 08:22 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Default Re: How to upload an image to DB in ASP.Net?

For example,
The image stored in a database whose name is called StoreImage...
Database contains five columns like(imgname,img type,imglength,imgbytes,loc)...
if we want to retrieve the iamge from database means,

first we have to give image name to database,here i am using dropdown list box for keeping the image name...
here the following code will explain of retrieve the image from database



string connection = System.Configuration.ConfigurationManager.AppSetti ngs["ConnectionString"];
SqlConnection conn = new SqlConnection(connection);
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("select img from StoreImage where imgname='" + DropDownList1.SelectedValue + "'", conn);
byte[] buffer = (byte[])cmd.ExecuteScalar();
SqlCommand cmd1 = new SqlCommand("select * from StoreImage where imgname='" + DropDownList1.SelectedValue + "'", conn);
rdr = cmd1.ExecuteReader();
string name = "";
int len = 0;
while (rdr.Read())
{
name = rdr.GetValue(0).ToString();
len = (int)rdr.GetValue(2);
}
string path = "E://Image-Retrive//image//" + name;
FileStream fls = new FileStream(path, FileMode.Append, FileAccess.Write);
fls.Write(buffer, 0, len);
Image1.Visible = true;
fls.Close();
Image1.ImageUrl = p;
rdr.Close();

hope u satisy by using this...
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 08-16-2007, 10:10 AM
H2o H2o is offline
D-Web Analyst
 
Join Date: Jul 2007
Posts: 246
H2o is on a distinguished road
Default Re: How to upload an image to DB in ASP.Net?

Hi

I got no error, but image not save in sqlserver database
if any idea.. pls help me


thanks
__________________
H2O

Without us, no one can survive..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 08-17-2007, 11:22 PM
krishnakumar krishnakumar is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 206
krishnakumar is on a distinguished road
Smile Re: How to upload an image to DB in ASP.Net?

Hi,

I think that we can't store the image, but we can store in the format of binary data of the image in sqlserver2005..... Datatype for store the binarydata is image....
__________________
Krishnakumar.S
Beware of Everything -that is un true; stick to the Truth shall succeed slowly but steadily

Last edited by krishnakumar : 08-30-2007 at 03:20 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 09-18-2007, 11:18 PM
kingmaker kingmaker is offline
D-Web Genius
 
Join Date: Jun 2007
Posts: 882
kingmaker is on a distinguished road
Send a message via Yahoo to kingmaker
Default Re: How to upload an image to DB in ASP.Net?

CREATE TABLE [dbo].[image] (
[img_pk] [int] IDENTITY (1, 1) NOT NULL ,
[img_name] [varchar] (50) NULL ,
[img_data] [image] NULL ,
[img_contenttype] [varchar] (50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[image] WITH NOCHECK ADD
CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED
(
[img_pk]
) ON [PRIMARY]
GO

UploadImage.aspx

<%@ Page language="c#" Src="UploadImage.aspx.cs" Inherits="DBImages.UploadImage" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
</HEAD>
<body bgcolor=#ffffff>

<form enctype="multipart/form-data" runat=server id=form1 name=form1>
<h3>The ASPFree Friendly Image Uploader</h3>
Enter A Friendly Name<input type=text id=txtImgName runat="server" >
<asp:RequiredFieldValidator id=RequiredFieldValidator1 runat="server" ErrorMessage="Required" ControlToValidate="txtImgName"></asp:RequiredFieldValidator>

<br>Select File To Upload:
<input id="UploadFile" type=file runat=server>
<asp:button id=UploadBtn Text="Upload Me!" OnClick="UploadBtn_Click" runat="server"></asp:button>
</form>


</body>
</HTML>


UploadImage.aspx.cs ( codebehind file)

using System;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DBImages
{
public class UploadImage : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button UploadBtn;
protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
protected System.Web.UI.HtmlControls.HtmlInputText txtImgName;
protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;

public UploadImage() { }

private void Page_Load(object sender, System.EventArgs e){ }

public void UploadBtn_Click(object sender, System.EventArgs e)
{
if (Page.IsValid) //save the image
{
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
string imgContentType = UploadFile.PostedFile.ContentType;
string imgName = txtImgName.Value;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);

int RowsAffected = SaveToDB( imgName, imgBinaryData,imgContentType);
if ( RowsAffected>0 )
{
Response.Write("<BR>The Image was saved");
}
else
{
Response.Write("<BR>An error occurred uploading the image");
}

}
}


private int SaveToDB(string imgName, byte[] imgbin, string imgcontenttype)
{
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
SqlCommand command = new SqlCommand( "INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( @img_name, @img_data,@img_contenttype )", connection );

SqlParameter param0 = new SqlParameter( "@img_name", SqlDbType.VarChar,50 );
param0.Value = imgName;
command.Parameters.Add( param0 );

SqlParameter param1 = new SqlParameter( "@img_data", SqlDbType.Image );
param1.Value = imgbin;
command.Parameters.Add( param1 );

SqlParameter param2 = new SqlParameter( "@img_contenttype", SqlDbType.VarChar,50 );
param2.Value = imgcontenttype;
command.Parameters.Add( param2 );

connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();

return numRowsAffected;
}
}
}

Web.Config

<configuration>
<appSettings>
<add key="DSN" value="server=localhost;uid=sa;pwd=;Database=aspfr ee"/>
</appSettings>
<system.web>
<customErrors mode="Off" />
</system.web>
</configuration>
__________________
The KINGMAKER
Makes Every Thing Possible

Stuffs (My Blog)
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Fckeditor Image Upload Path bluesky PHP Programming 1 03-24-2008 06:12 AM
Convert image to other image format using CODEC in .NET 3.0 Mramesh C# Programming 0 02-07-2008 03:33 AM
How to create an image from panel background Image S.Vinothkumar C# Programming 1 10-22-2007 03:52 AM
Example of Image Upload hanusoft ASP and ASP.NET Programming 2 09-20-2007 10:59 PM
Image Upload problem ewriter PHP Programming 4 07-13-2007 05:18 AM


All times are GMT -7. The time now is 12:55 PM.


Copyright ©2004 - 2007, DiscussWeb. All Rights Reserved.

SEO by vBSEO 3.0.0