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

Posted by Hala Qaseam on Stack Overflow See other posts from Stack Overflow or by Hala Qaseam
Published on 2012-10-02T14:38:00Z Indexed on 2012/10/02 15:37 UTC
Read the original article Hit count: 142

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about sql-server