【问题标题】:Insert image to database with FileUpload使用 FileUpload 将图像插入数据库
【发布时间】:2012-03-23 14:09:32
【问题描述】:

我想使用 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,关键字“用户”附近的语法不正确。我已经尝试过小于 10KB 大小的 *.jpg 和 *.png 文件。

【问题讨论】:

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


    【解决方案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";
    

    【讨论】:

    • 谢谢你这工作,但我找到了另一种方法。还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多