I wanted to test storing images on a database, so I did a Google search and found this code:
.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Data.SqlClient;
using System.IO;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strImageName = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + strImageName);
Bitmap bNewImage = new Bitmap(strImageName);
FileStream fs = new FileStream(strImageName, FileMode.Open, FileAccess.Read);
//creating byte array to read image
byte[] bImage = new byte[fs.Length];
fs.Read(bImage, 0, Convert.ToInt32(fs.Length));
fs.Close();
fs = null;
string connstr = "Server=WINSP3UE\\SqlExpress;Database=ImageStore;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string strQuery;
strQuery = "insert into [dbo].[ImageStore](id,[ImageContent]) values(" + "1," + " @pic)";//"INSERT INTO ImageStore (ID, ImageContent) values (" + "1," + " @pic)";
SqlParameter ImageParameter= new SqlParameter();
ImageParameter.SqlDbType = SqlDbType.Image;
ImageParameter.ParameterName = "pic";
ImageParameter.Value = bImage;
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add(ImageParameter);
cmd.ExecuteNonQuery();
Response.Write("Image has been added to database successfully");
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}
.aspx file
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<div>
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" />
</div>
</form>
It should work but it isn't, and by that I mean it doesn't update the database, the values in the tables remain null. And the message "Image has been uploaded to your database successfully" doesn't appear either. The database I am using has one table named ImageStore with two attributes, ID and ImageContent.
I am new to asp.net and c#, could anyone please check the code for any errors?