简体   繁体   English

使用ASP.NET中的FileUpload更新SQL中的图像

[英]Update image in SQL using FileUpload in ASP.NET

I'm trying to store profile images for users in SQL. 我正在尝试在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. 我要保存图像的列具有image作为数据类型。

Here is my code: 这是我的代码:

UPDATE: Code updated and working. 更新:代码已更新并且可以正常工作。 The problem was the parameters used in the query. 问题是查询中使用的参数。 Many thanks to SeM and Crowcoder! 非常感谢SeM和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. 转换为字节数组是可行的,但我不知道问题可能出在哪里。

Remove the using(SqlDataAdapter sda = new SqlDataAdapter()){} , then change that part like this: 删除using(SqlDataAdapter sda = new SqlDataAdapter()){} ,然后按如下所示更改该部分:

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. 捕获异常并从数据库或查询字符串中检查问题。

Use try-catch block to know the exception you get. 使用try-catch块可以知道您得到的异常。

Remove the sql data adapter since you didn't use it. 删除sql数据适配器,因为您没有使用它。

Try referring this link . 尝试引用此链接

exec sp_executesql N'UPDATE Users SET Image=@data WHERE Username=@user',N'@data image,@user nvarchar(35)',@data=default,@user=N'System.Web.UI.WebControls.LoginName' - Found this in profiler exec sp_executesql N'UPDATE用户SET Image = @ data WHERE Username = @ user',N'@ data image,@ user nvarchar(35)',@ data = default,@ user = N'System.Web.UI.WebControls。 LoginName'-在分析器中找到此

Assuming LoginName1 is a TextBox , you must access the Text property to get the value. 假设LoginName1是一个TextBox ,则必须访问Text属性以获取该值。 If you ToString() a control you get what you are seeing, the name of the control: System.Web.UI.WebControls.LoginName 如果使用ToString()控件,则得到的是控件的名称: System.Web.UI.WebControls.LoginName

You must do: 您必须做:

cmd.Parameters.Add(new SqlParameter("@user", LoginName1.Text));

UPDATE: 更新:

I should have noticed that LoginName1 is not a TextBox. 我应该注意到LoginName1不是TextBox。 You may have to access the User property, I don't see a property on LoginName control to get the value but maybe I'm just missing it. 您可能必须访问User属性,我没有在LoginName控件上看到属性来获取该值,但也许我只是缺少它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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