使用FileUpload将图像插入数据库

时间:2012-03-23 14:09:33

标签: asp.net sql linq-to-sql file-upload image-uploading

我想使用FileUpload控件将图像插入到我的数据库中。我尝试使用以下代码执行此操作:

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";
            }*/
        }
    }

但我在cmd.ExecuteNonQuery()上遇到错误;其中说:SqlException未被用户代码处理,关键字“User”附近的语法不正确。我已经尝试了大小不超过10KB的* .jpg和* .png文件。

1 个答案:

答案 0 :(得分:1)

您遇到语法错误:

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

缺少)并且在那里间隔:

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

或者,更好的是(为什么要连接?):

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