Search code examples
c#asp.netsqlconnection

Update image in SQL using FileUpload in ASP.NET


I'm trying to store profile images for users in SQL. My problem is that nothing is saved in the database table. The column where I want to save the image has image as datatype.

Here is my code:

UPDATE: Code updated and working. The problem was the parameters used in the query. Many thanks to SeM and Crowcoder!

protected void ButtonPic_Click(object sender, EventArgs e)
    {
        string filePath = FileUpload1.PostedFile.FileName;
        string filename = Path.GetFileName(filePath);
        string ext = Path.GetExtension(filename);
        string contenttype = string.Empty;
        string username = User.Identity.Name; // Gets the current username

        switch (ext)
        {
            case ".jpg":
                contenttype = "image/jpg";
                break;
            case ".png":
                contenttype = "image/png";
                break;
        }

        if (contenttype != string.Empty)
        {
            Stream fs = FileUpload1.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            byte[] bytes = br.ReadBytes((int)fs.Length + 1);

            string base64String = Convert.ToBase64String(bytes, 0,   bytes.Length);
            Image1.ImageUrl = "data:image/png;base64," + base64String;

            string constr = ConfigurationManager.ConnectionStrings["LoginDBConnectionString"].ConnectionString;
            string strQuery = "UPDATE Users SET Image=@data WHERE Username=@user";

            try
            {
                using (SqlConnection con = new SqlConnection(constr))
                {
                    con.Open();
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Add(new SqlParameter("@data", bytes)); 
                        cmd.Parameters.Add(new SqlParameter("@user", username));
                        cmd.CommandText = strQuery;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        else
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "Filformat stöds inte." +
              " Endast jpg/png är tillåtet";
        }
    }

The conversion to a byte array is working but I can't figure out where the problem could be.


Solution

  • Remove the using(SqlDataAdapter sda = new SqlDataAdapter()){}, then change that part like this:

    try
    {
        using (SqlConnection con = new SqlConnection(constr))
        {
            con.Open();
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add(new SqlParameter("@data", bytes));
                cmd.Parameters.Add(new SqlParameter("@user", LoginName1.ToString()));
                cmd.CommandText = strQuery;
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch(Exception ex)
    {
        //Handle your exception   
    }
    

    catch your exception and check problems from database or query string.