There are number of options to store images, one popular option is to store images in database. But generally we do not prefer to store images in database because of , its take longer time to store in database that storing in directory.
Here is simple sample code to store images in database. First programmer need to create a table with column type image in database and then insert image in table using c# code.
Please let us know if you face any problem in this code.
Step1: Create an Table in Sql Server Database.
CREATE TABLE [dbo].[Demo](
[DemoImageName] [varchar] (50),
[DemoImage] [image] NULL
)
Step 2: Write a code to save select image into Database table.
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] imageSize = newbyte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (
int)FileUpload1.PostedFile.ContentLength);
// Create SQL Connection
SqlConnection sqlConn = newSqlConnection("Data Source=Server Name;Initial Catalog=DatabaseName;Integrated Security=True");
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText =
"INSERT INTO DemoImages(DemoImageName,Image)" +
" VALUES (@DemoImageName,@DemoImage)";
cmd.CommandType =
CommandType.Text;
cmd.Connection = sqlConn;
SqlParameter ImageName = newSqlParameter("@ImageName", SqlDbType.VarChar, 50);
ImageName.Value = FileUpload1.FileName;
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = newSqlParameter("@Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
sqlConn.Open();
int result = cmd.ExecuteNonQuery();
sqlConn.Close();
if (result > 0) lblMessage.Text = "Demo File Uploaded and Saved";
}
0 comments:
Post a Comment