0

i have a database column 'images' which can hold binary data, for some reason the images doesnt want to upload. it doest pull any exceptions or aything wrong with the code:

here is extracts of the code

protected void BtnAdd_Click(object sender, EventArgs e)
    {
     string imgpath = FileUploadImage.FileName.ToString();
     DBConnectivity.Add(imgpath);
    }
here is the DBCoectivity Class:
public static void Add(string imgpath)
    {
        byte[] imgbt = null;
        FileStream fstream = new FileStream(imgpath, FileMode.Open, FileAccess.Read);
         BinaryReader BR = new BinaryReader(fstream);
         imgbt = BR.ReadBytes((int)fstream.Length);

        SqlConnection myConnection = GetConnection();
        string myQuery = "INSERT INTO images( imagePath) VALUES ( @IMG )";
        SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
        try
        {
            myConnection.Open();
            myCommand.Parameters.Add(new SqlParameter("@IMG",imgbt)); 
            myCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in DBHandler", ex);
        }
        finally
        {
            myConnection.Close();
        }
    }

1 Answer 1

1

This snippet works for me:

byte[] imgbt = null;

if (FileUploadImage.HasFile)
{
    Stream photoStream = FileUploadImage.PostedFile.InputStream;
    imgbt = new byte[FileUploadImage.PostedFile.ContentLength];
    photoStream.Read(imgbt, 0, FileUploadImage.PostedFile.ContentLength);
}

Also, you were inserting the image name (misspelled as parameter to Add method and bad choice of variable name as it is not a path) into the database, not the binary data. It should read:

string myQuery = "INSERT INTO images(imgbt) VALUES (@IMG)";

Here's a sample tutorial which explains it better:

File Upload with ASP.NET

Sign up to request clarification or add additional context in comments.

1 Comment

Updating answer with tutorial link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.