The next part is Simple write a Stored Procedure that can insert data into the table
you must have a table that has "varbinary" Type to store an image like the one below
CREATE TABLE [dbo].[Image](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Caption] [nvarchar](50) NOT NULL,
[Content] [varbinary](max) NOT NULL,
)
and the Stored Procedure to store should look something like this
CREATE PROC InsertNewImage
@Caption varchar(50),
@Content varbinary(max)
AS
INSERT INTO [DummyDatabase].[dbo].[Image] ([Caption], [Content])
VALUES (@Caption, @Content)
and the Stored Procedure to retrieve should look like this
CREATE PROC GetImageByID
@ID int
AS
SELECT Caption, Content FROM Image WHERE ID = @ID
now in your code you should have a Function like this
public void InsertImage(string imageName, string imagePath)
{
System.IO.FileStream fs = new System.IO.FileStream(imagePath, System.IO.FileMode.Open);
byte[] imageAsBytes = new byte[fs.Length];
fs.Read(imageAsBytes, 0, imageAsBytes.Length);
fs.Close();
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=DummyDatabase;Integrated Security=True");/
string insertString = "[dbo].[InsertNewImage]";
SqlCommand insertCommand = new SqlCommand(insertString, conn);
insertCommand.CommandType = CommandType.StoredProcedure;
insertCommand.Parameters.Add("@Caption", SqlDbType.VarChar).Value = imageName ;
insertCommand.Parameters.Add("@Content", SqlDbType.VarBinary).Value = imageAsBytes;
try
{
conn.Open();
insertCommand.ExecuteNonQuery();
}
catch(SqlException ex)
{
//handle the ex Exception
}
finally
{
conn.Close();
}
}
and retrieve the images the following code can be used
public Image GetImageById(int imageID)
{
Image result = null;
SqlDataReader imageReader;
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=DummyDatabase;Integrated Security=True");
string selectString = "[dbo].[GetImageByID]";
SqlCommand selectCommand = new SqlCommand(selectString, conn);
selectCommand.CommandType = CommandType.StoredProcedure;
selectCommand.Parameters.AddWithValue("@ID", imageID.ToString());
conn.Open();
imageReader = selectCommand.ExecuteReader(CommandBehavior.CloseConnection);
while(imageReader.Read())
{
result = Image.FromStream(new MemoryStream((byte[])imageReader.GetValue(1)));
}
return result;
}
in your code you would call your function like this
public void Capture()
{
var stream = Request.InputStream;
string dump;
using (var reader = new StreamReader(stream))
dump = reader.ReadToEnd();
var path = Server.MapPath("~/visitorimages/");
InsertImage("Visitors Image",path)
}
Thank you for posting at Dotnetfunda
[Administrator]
Shail, if this helps please login to Mark As Answer. | Alert Moderator