Updating and retrieving images (Asp.net c#) - c#

protected void upimg_about_Click(object sender, EventArgs e)
{
con.Open();
string sqlQuery = " UPDATE [dbo].[tbldetails] SET [image]=#image,[image2]=#image2 WHERE id=#id";
SqlCommand cmd2 = new SqlCommand(sqlQuery, con);
cmd2.Parameters.AddWithValue("#id", Session["email"].ToString());
int img = Image1.PostedFile.ContentLength;
int img2 = Image2.PostedFile.ContentLength;
byte[] msdata = new byte[img];
byte[] msdata2 = new byte[img2];
Image1.PostedFile.InputStream.Read(msdata, 0, img);
Image2.PostedFile.InputStream.Read(msdata2, 0, img2);
cmd2.Parameters.AddWithValue("#image", msdata);
cmd2.Parameters.AddWithValue("#image2", msdata2);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd2.ExecuteNonQuery();
con.Close();
data1.Text="Image Updated Successfully";
}
This is the code I am using to update the images in the database.
The user when required can update the images (eg: in the firstpage.aspx) and can retrieve it in the next page (nextpage.aspx).
But the problem is: suppose a user wants to update just a single image and he/she upload's the image and clicks the update button and when retrieving images in the next page the image that was updated is visible but the one which is already present in the database is not. I am not sure but during the updation the other fileupload is empty is this why this is happening? Is there other way to do it?
PS: I have textboxes in the firstpage.aspx in which i am retrieving the text he/she has already put in the database and hence when the user wants to make changes it can be done easily.
TextBox1.Text = dr["name"].ToString();
TextBox2.Text = dr["address"].ToString();
So, is it possible to retrieve the image path which the user has previously submitted? Or any way in which the user can update a single image and during retrieval both the images can be retrieved?
Thank You! :)

Break your code up so that you can send 1 image at a time to the DB. Then pass the corresponding FileUpload and SQL Column name to your function. Conditionally send the new file to the database depending on whether the FileUpload contains a file. You can check this by looking at the HasFile property.
protected void upimg_about_Click(object sender, EventArgs e)
{
// make sure at least 1 file
if (!Image1.HasFile && !Image2.HasFile)
{
data1.Text="No Images Uploaded";
return;
}
con.Open();
UploadImage(Image1, "[image]");
UploadImage(Image2, "[image2]");
con.Close();
data1.Text = "Image Updated Successfully";
}
void UploadImage(FileUpload fileUpload, string columnName)
{
if (!fileUpload.HasFile)
{
return;
}
string sqlQuery = "UPDATE [dbo].[tbldetails] SET " + columnName + "=#image WHERE id=#id";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("#id", Session["email"].ToString());
int img = fileUpload.PostedFile.ContentLength;
byte[] msdata = new byte[img];
fileUpload.PostedFile.InputStream.Read(msdata, 0, img);
cmd.Parameters.AddWithValue("#image", msdata);
cmd.ExecuteNonQuery();
}

Related

C# - Click inside the dataGridView for bigger picture

I have a dataGridView populated with data from an MS SQL database. The data also contains images with small dimensions (140x195).
Is there any way to click to the image and open a bigger picture?
Image here
I am using the following code to show the picture to the pictureBox.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.CurrentRow.Selected = true;
int cardNo = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Number"].FormattedValue);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ImageFull FROM SS4 WHERE CardNo = '" + cardNo+"'", con);
string img = cmd.ExecuteScalar().ToString();
pbCard.Image = Image.FromFile(img);
con.Close();
}
The path for the image is saved to the database.
I cannot find a way to show the picture to a new form instead to a pictureBox.

Compare an image loaded in a picture box and a BLOB stored in MySQL

I have an image loaded into a picture box and some images saved as BLOB in MySQL.
I want to retrieve some data from the row if this image in the picture box is same as the one saved in the database.
There should be only one match and if it doesn't match, should prompt a message as "No match".
I'm using C#, MySQL and Visual Studio.
I don't know how to do this exactly, I'm new to C# and I don't get the output as I want. Maybe I should first convert the IMAGE in the picture box to something else??
Here is what I've come up so far. Any suggestion is highly appreciated.
private void button8_Click(object sender, EventArgs e)
{
// Check button
Image ori_histoImage = histogram_pictureBox.Image;
byte[] histo = (Byte[])new ImageConverter().ConvertTo(ori_histoImage, typeof(byte[]));
string histoS = System.Convert.ToBase64String(histo);
try
{
string MyConnection = "datasource=127.0.0.1;port=3306;username=root;password=;database=ahbis";
string sql = "SELECT * FROM criminal WHERE palmHistogram= '" + histo + "';";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand(sql, MyConn);
int count = Convert.ToInt32(MyCommand.ExecuteScalar());
MySqlDataReader MyReader;
MyConn.Open();
MyReader = MyCommand.ExecuteReader();
while (MyReader.Read())
{
if(count !=1)
{
MessageBox.Show("No match");
string cid = (MyReader["CID"].ToString());
textBox1.Text = cid;
}
else
MessageBox.Show("No match");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When you save the blob into the db, as Raymond suggested, also store a checksum field in your database. You can check this link Calculate MD5 checksum for a file
When trying to look for the blob, redo the function to create the checksum. Now instead of comparing the two blobs, you can compare the two check sums. Once again, if it doesn't work, print the sql and make sure the sql is created right.

C# Web App adding data twice to database

I've tried a few things I've read on StackOverflow with some other topics with no success.
public partial class Content_Management : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Code fires EVERY TIME a Row is selected in the Gridview control
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//Extract upload Title and assign to relevant Textbox control
TextBox1.Text = GridView1.SelectedRow.Cells[2].Text.ToString();
//Extract upload album name and assign to relevant Textbox control
TextBox3.Text = GridView1.SelectedRow.Cells[3].Text.ToString();
//Extract upload Image and assign to relevant Image control
Image4.ImageUrl = "~/uploadedimages/" + GridView1.SelectedRow.Cells[5].Text.ToString();
//Extract upload Status and assign to DropDownList control
DropDownList1.Text = GridView1.SelectedRow.Cells[8].Text.ToString();
//Enable the "Update" Button control
Button2.Enabled = true;
//Extract upload Multimedia Clip and load into MediaPlayer control ready for playing
Media_Player_Control1.MovieURL = Server.MapPath("~/uploaded_multimedia/" + GridView1.SelectedRow.Cells[5].Text.ToString());
}
//This code will execute EVERY TIME "Save" Button is clicked
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Birdspotting"].ConnectionString);
//Then I would reference the string e.g
//Create variable to point to image upload folder
string image_folder = Server.MapPath("~\\uploadedimages\\");
//Create 2 variables and set the file names to blank in case User does not upload any files - DB entries will still be made
string dbfilename1 = "";
string dbfilename2 = "";
//Check if the Image Fileupload control has a file or not
if (FileUpload1.HasFile)
{
//If the Fileupload control has a file, change the value of the variable to the selected image file name
string filename1 = FileUpload1.FileName.ToString();
//Copy the selected Image file from the Users device accross the Internet and save it into the Image folder within the Web App structure
FileUpload1.SaveAs(image_folder + filename1);
//Assign the new file name to the variable used to populate the DB - change from "" to actual file name
dbfilename1 = filename1;
}
//Repeat as above for Multimedia Clip - audio or video
string multimedia_folder = Server.MapPath("~\\uploaded_multimedia\\");
if (FileUpload2.HasFile)
{
string filename2 = FileUpload2.FileName.ToString();
FileUpload2.SaveAs(multimedia_folder + filename2);
dbfilename2 = filename2;
}
//Create DB Connection - point to SQL
// create sql connection object. make sure to put a valid connection string
SqlCommand cmd = new SqlCommand("Insert into LeagueTable" + "(BirdName, Quantity, ArtworkImage, MediaClip, Username, Datetime, ActiveStatus, UserId)"
+ "Values(#1, #2, #3, #4, #5, #6, #7, #8) Select SCOPE_IDENTITY()");
//SqlXml newXml = new SqlXml(new XmlTextReader("Birds.xml"));
using (SqlDataAdapter sda = new SqlDataAdapter())
{
//Define the structure of the SQL Statement - used to executed instructions against the DB Table
//The DB Table name and each field is indentified in the command.
//INSERT commands includes Primary Key insertion -that is generated by the DB itself
cmd.Parameters.AddWithValue("#1", TextBox1.Text.ToString());
cmd.Parameters.AddWithValue("#2", TextBox3.Text.ToString());
cmd.Parameters.AddWithValue("#3", dbfilename1.ToString());
cmd.Parameters.AddWithValue("#4", dbfilename2.ToString());
cmd.Parameters.AddWithValue("#5", User.Identity.Name);
cmd.Parameters.AddWithValue("#6", DateTime.Now.ToString());
cmd.Parameters.AddWithValue("#7", DropDownList1.Text.ToString());
cmd.Parameters.AddWithValue("#8", System.Data.SqlDbType.Int);
cmd.Connection = conn;
try
{
conn.Open();
var added = cmd.ExecuteNonQuery();
lblConfirm.Text = added.ToString() + "Record Inserted.";
}
catch (Exception ex)
{
lblError.Text = "Error Inserting Record";
lblError.Text += ex.Message;
}
finally
{
conn.Close();
}
GridView1.DataBind();
}
}

Saving multiple Images at once to the database with a FileUpload Control

I am working on a company Blog site, and when a user is making a post, they can add an image from their computer to the post. I used a FileUpload control to do this, and it works great. However, I am trying to change the functionality to allow the user to select and upload multiple images in one post, and I am running into some issues. I have set the 'allow multiple' property to 'true', however once multiple images are selected into the control (Image URLs get separated by a comma) and the post button is clicked, only one of the images is inserted into the database, but it is inserted as many times as images there are, and only that one image is displayed on the blog post. So if I try to add three different images, it inserts three instances of the first image into the database. The code corresponding to the the FileUpload in my onClick function is below:
if (imageUpload.HasFile == true)
{
SqlCommand maxMessId = new SqlCommand("SELECT Max(MessageID) FROM BlogMessages", conn);
lastMessageID = Convert.ToInt32(maxMessId.ExecuteScalar());
foreach (var uploadedFile in imageUpload.PostedFiles)
{
SqlCommand cmdInsertImage = new SqlCommand("INSERT INTO BlogImages(Image, MessageID) VALUES (#Image, #MessageID)", conn);
cmdInsertImage.Parameters.AddWithValue("#Image", SqlDbType.Image).Value = imageUpload.FileBytes;
cmdInsertImage.Parameters.AddWithValue("#MessageID", lastMessageID);
cmdInsertImage.ExecuteNonQuery();
}
}
I am thinking the issue could be with:
cmdInsertImage.Parameters.AddWithValue("#Image", SqlDbType.Image).Value = imageUpload.FileBytes;
If that is getting the file bytes for only one image.. I am not sure how to get the filebytes for both files. The image column in my BlogImages table is of the type Image.
Any suggestions are much appreciated!
Are you sure that you're working on the right way ?????PostesFiles are the list of file and each one has it own properties you need to read from there.....nothing else
Here a simples examples
For Each xx In fp.PostedFiles
xx.InputStream
xx.ContentLength
xx.FileName
Next
Where those properties upon expose Inputstrem a stream of the image,ContenteLenght it lenght, Filename the filename of the images.So when you pass the imageupload.FileBytes is not the correct way to achive your goal.You have to read the stream and return a bytearray to save the data withing your sql server.Nothing else i hope it could help you to solve your issue.
UPDATE*
Assume that you're into the foreach loop for each single file you have to setup its own bytearray
MemoryStream ms = new MemoryStream();
file.PostedFile.InputStream.CopyTo(ms);
var byts = ms.ToArray();
ms.Dispose();
then
change your insert statement like this
cmdInsertImage.Parameters.AddWithValue("#Image", SqlDbType.Image).Value = byts;
not tested but it should solve the issue.
UPDATE 2
if (test.HasFiles) {
StringBuilder sb = new StringBuilder();
foreach (void el_loopVariable in test.PostedFiles) {
el = el_loopVariable;
sb.AppendLine("FILENAME:<B>" + el.FileName.ToString + "</B><BR/>");
MemoryStream ms = new MemoryStream();
el.InputStream.CopyTo(ms);
byte[] byts = ms.ToArray;
ms.Dispose();
sb.AppendLine(string.Join(";", byts));
sb.AppendLine("<br/<br/>");
byts = null;
}
LitResponse.Text = sb.ToString;
}
I think the issue is that in your for each loop, you're stepping through the posted files, but you're still just using ImageUpload.FileBytes each time, which I expect would be returning the same thing each time.
I'm not super familiar with the file upload control, but maybe you can use the ContentLength property of your uploaded file object to index into the byte array returned by ImageUpload.FileBytes (assuming that array contains each of the multiple files).
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strImageName = txtImage.Text.ToString(); //to store image into sql database.
if (FileUpload1.PostedFile != null &&
FileUpload1.PostedFile.FileName != "")
{
byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Pictures(ID,ImageName,Image)" +
" VALUES (#ID,#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
//retrieve latest ID from tables which was stored in session.
int ID = Convert.ToInt32(System.Web.HttpContext.Current.Session["ID"].ToString());
SqlParameter ID = new SqlParameter
("#ID", SqlDbType.Int, 5);
ID.Value = (Int32)ID;
cmd.Parameters.Add(ID);
SqlParameter ImageName = new SqlParameter
("#ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter("#Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
lblMessage.Text = "File Uploaded";
lblSuccess.Text = "Successful !";
}}

upload new file first check if this file exist already in database or not then if not exist save that in database

I'm trying to create sql database that contains
Image Id (int)
Imagename (varchar(50))
Image (image)
and in aspx write in upload button this code:
protected void btnUpload_Click(object sender, EventArgs e)
{
//Condition to check if the file uploaded or not
if (fileuploadImage.HasFile)
{
//getting length of uploaded file
int length = fileuploadImage.PostedFile.ContentLength;
//create a byte array to store the binary image data
byte[] imgbyte = new byte[length];
//store the currently selected file in memeory
HttpPostedFile img = fileuploadImage.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename = txtImageName.Text;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)", connection);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
When I'm uploading a new image I need to first check if this image already exists in database and if it doesn't exist save that in database.
Please how I can do that?
Add a method that is responsible for checking if the filename already exists in the table.
private bool FileExists(string imageName)
{
using (SqlConnection conn = new SqlConnection()) // establish connection
{
using (SqlCommand cmd =
new SqlCommand("select 1 where exists(select Id from Image where ImageName = #)", conn))
{
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imageName;
return cmd.ExecuteNonQuery() > 0;
}
}
}
Then I would call this like so
if (fileuploadImage.HasFile && !FileExists(txtImageName.Text))
{
...
string cmd ="if not exists (select * from Image where ImageName= #imagename); ";
\\if you want to check image data
\\ (select * from Image where SUBSTRING(ImageName, 1, 8000)= SUBSTRING(#imagename, 1, 8000) );
string cmd += "INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";
SqlCommand cmd = new SqlCommand(cmd, connection);
If you want to verify imagedata, You can try to use DATALENGTH as first line of check for the two images.
If the DATALENGTH is different, then you suppose to have a "different" picture".
You can also use SUBSTRING(Image, 1, 8000) to check first 8000 bytes.
And also SUBSTRING(Image, DATALENGTH(Image) - 7999, 8000) to check last 8000 bytes.
One of the fastest ways is to do an UPDATE and then INSERT if update returns no updates.
string cmd = #"UPDATE Image SET Image = #imagedata WHERE ImageName = #ImageName
IF ##ROWCOUNT=0
INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";
Or if query on Image itself:
string cmd = #"UPDATE Image SET ImageName = #ImageName WHERE Image = #imagedata
IF ##ROWCOUNT=0
INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";

Categories

Resources