- Forum
- Databases
- SQL Server - How to store a picture in sql server 2000?
-
How to store a picture in sql server 2000?
How to store a picture in sql server 2000?
I am using Asp.net please help me
-
Junior Member
Re: How to store a picture in sql server 2000?
There are 2 ways to do so.
1. Store the actual image on the file system or on the web server and just point that url in sql server. This is the simple and best way especially if you want to show those images in browser
2. Convert those images into binary streams and then store them in sqlserver.
Here is the code:
using System.Data.SqlClient;
using System.IO
protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
protected System.Web.UI.WebControls.Button UploadBtn;
protected System.Web.UI.HtmlControls.HtmlInputText txtImgName;
protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;
private void UploadMe_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 = Save( imgName, imgBinaryData,imgContentType);
if ( RowsAffected>0 )
{
Response.Write("
The Image was saved");
}
else
{
Response.Write("
An error occurred uploading the image");
}
}
}
private int Save(string imgName, byte[] imgbin, string imgcontenttype)
{
SqlCommand command = new SqlCommand( "INSERT INTO tbl_Image (img_name,img_data,img_contenttype) VALUES ( @img_name, @img_data,@img_contenttype)", con );
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 );
con.Open();
int numRowsAffected = command.ExecuteNonQuery();
con.Close();
return numRowsAffected;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules