簡體   English   中英

使用FileUpload將圖像插入數據庫

[英]Insert image to database with FileUpload

我想使用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文件。

您有語法錯誤:

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";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM