简体   繁体   中英

Insert image to database with FileUpload

I want to insert an image to my database using a FileUpload control. I have tried to do this with the following code:

protected void btnUploadAvatar_Click(object sender, EventArgs e)
    {
        if (fuAvatar.PostedFile != null && fuAvatar.PostedFile.FileName != "") ;
        {
            byte[] imageSize = new byte[fuAvatar.PostedFile.ContentLength];

            HttpPostedFile uploadImage = fuAvatar.PostedFile;

            uploadImage.InputStream.Read(imageSize, 0, fuAvatar.PostedFile.ContentLength);

            SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");

            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = "INSERT INTO User(image" + "VALUES (@Image) WHERE userid = @Userid";

            cmd.CommandType = CommandType.Text;

            cmd.Connection = con;

            SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, imageSize.Length);
            UploadedImage.Value = imageSize;

            SqlParameter userid = new SqlParameter("@Userid", SqlDbType.Int);
            userid.Value = Convert.ToInt32(Session["userid"]);

            cmd.Parameters.Add(userid);
            cmd.Parameters.Add(UploadedImage);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            /*if(result > 0)
            {
                lblResult.Text = "Avatar lastet opp";
            }*/
        }
    }

But i get a error on cmd.ExecuteNonQuery(); which says: SqlException unhandled by user code, Incorrect syntax near the keyword 'User'. I have tried both *.jpg and *.png files of under 10KB size.

You have a syntax error:

cmd.CommandText = 
            "INSERT INTO User(image" + "VALUES (@Image) WHERE userid = @Userid";

There is a missing ) and spacing there:

cmd.CommandText = 
          "INSERT INTO User(image)" + " VALUES (@Image) WHERE userid = @Userid";

Or, better yet (why concatenate at all?):

cmd.CommandText = 
          "INSERT INTO User(image) VALUES (@Image) WHERE userid = @Userid";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM