【问题标题】:Asp.Net Adding Images to SQL Table...What am I doing wrong?Asp.Net 将图像添加到 SQL 表...我做错了什么?
【发布时间】:2009-04-08 12:55:49
【问题描述】:

我以前也这样做过,但方式不同。我试图让下面的代码工作。如果我不投射“OriginalPhoto”或“Thumbnail”,则会发生错误。不允许从数据类型 varchar 到 varbinary(max) 的隐式转换。使用 CONVERT 函数运行此查询。我不明白为什么它要求演员。但是,如果我确实投射它,图像以二进制数据格式添加到数据库中就好了。尝试查看图像时,我收到错误“无法显示给定数据”。我已经使用 SqlDataAdapter 将两个 byte[] 插入到表中,并且可以正常工作。我想使用这种方法,但我做错了什么?

个人资料表包含:

用户 ID nvarchar(50)
标题 nvarchar(10)
OriginalImage varbinary(max)
ThumbImage varbinary(max)

protected void AddPhotoToDatabase()
{
    byte[] OriginalPhoto = GetImage();
    byte[] Thumbnail = GenerateThumbnail();
    string Title = FileUpload1.FileName.ToString();
    string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES ('" + User.Identity.Name + "', '" + Title + "', CAST('" + OriginalPhoto + "'AS VARBINARY(MAX)), CAST('" + Thumbnail + "'AS VARBINARY(MAX)))";
    string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
    SqlConnection conn = new SqlConnection(strCon);
    SqlCommand comm = new SqlCommand(sql, conn);
    conn.Open();
    comm.ExecuteNonQuery();
    conn.Close();
}

protected byte[] GetImage()
{
    byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
    FileUpload1.PostedFile.InputStream.Read(photo, 0, photo.Length);
    return photo;
}

protected byte[] GenerateThumbnail()
{
    System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
    double thumbwidth = 0;
    double thumbheight = 0;
    double imgsz = 150.0;
    if (imgsz / image.Width < imgsz / image.Height)
    {
        thumbwidth = image.Width * (imgsz / image.Width);
        thumbheight = image.Height * (imgsz / image.Width);
    }
    else
    {
        thumbwidth = image.Width * (imgsz / image.Height);
        thumbheight = image.Height * (imgsz / image.Height);
    }
    System.Drawing.Image thumb = image.GetThumbnailImage((int)thumbwidth, (int)thumbheight, delegate() { return false; }, (IntPtr)0);
    MemoryStream ms = new MemoryStream();
    thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    return ms.ToArray();
}

【问题讨论】:

    标签: c# asp.net sql image insert


    【解决方案1】:

    你应该使用sql参数:

    using( SqlConnection cnn = GetConnection() ) {
        using( SqlCommand cmd = cnn.CreateCommand() ) {
            cmd.CommandText = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES (@UserId, @Title, @OriginalPhoto, @Thumbnail)";
            cmd.Parameters.AddWithValue( "@UserId", User.Identity.Name );
            cmd.Parameters.AddWithValue( "@Title", Title );
            cmd.Parameters.AddWithValue( "@OriginalPhoto", OriginalPhoto );
            cmd.Parameters.AddWithValue( "@Thumbnail", Thumbnail );
    
            cnn.Open();
            cmd.ExecuteNonQuery();
            cnn.Close();
        }
    }
    

    【讨论】:

    • 谢谢!你太棒了……哇,真让人头疼。我什至不在乎为什么我的方法不起作用。现在我知道为什么每个人都这样做了。谢谢!
    【解决方案2】:

    不要尝试将数据构建到插入查询中。试试这个:

    string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage],
                  [ThumbImage]) VALUES (@userId, @title, @originalImage, @thumbImage)";
    
    
    string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
    
    SqlConnection conn = new SqlConnection(strCon);
    SqlCommand comm = new SqlCommand(sql, conn);
    
    comm.Parameters.Add(new SqlParameter("@userId", User.Identity.Name));
    comm.Parameters.Add(new SqlParameter("@title", Title));
    comm.Parameters.Add(new SqlParameter("@originalImage", OriginalPhoto));
    comm.Parameters.Add(new SqlParameter("@thumbImage", Thumbnail));
    

    【讨论】:

      【解决方案3】:

      仅查看您的代码,我有点担心您对 SQL 注入攻击持开放态度。为了帮助减轻这种情况,还应该解决您的问题。您需要使用参数化查询。类似的东西

      cmd.CommandText="Insert into [ProfileGallery]" +
                      "(UserId,OriginalPhoto) values (@UserId,@OriginalPhoto)";
      cmd.Parameters.AddWithValue("UserId",User.Identity.Name);
      cmd.Parameters.AddWithValue("OriginalPhoto",OriginalPhoto);
      

      您的代码失败的原因可以通过这个示例应用程序看出:

      static void Main(string[] args)
      {
          byte[] byteArray = new byte[] { 1, 2, 0 };
          Console.WriteLine("This is my byte array: " + byteArray);
          Console.ReadLine();
      }
      

      这输出这是我的字节数组:System.Byte[]

      您可以将字节数组添加到字符串中,这让我有点震惊,尤其是因为它只是为我们提供了类型的名称。

      【讨论】:

        【解决方案4】:
        protected void Page_Load(object sender, EventArgs e)
            {
                 if (!IsPostBack)
                    {
                        BindData();
                    }
                }
            private void BindData()
            {
                SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
                string strSQL = "Select * from table6";
                SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn);
                DataSet ds = new DataSet();
                dt.Fill(ds);
                grd1.DataSource = ds;
                grd1.DataBind();
                cn.Close();
            }
            protected void btn1_Click(object sender, EventArgs e)
            {
                if(fileupload.HasFile)
                {
        
                    string imageSrc = "~/Image/" +fileupload.PostedFile.FileName;
                 string ImageName = txt1.Text;
                SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
                cn.Open();
                string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')";
                SqlCommand cmd = new SqlCommand(strSql, cn);
                cmd.ExecuteNonQuery();
                cn.Close();
                BindData();
                txt1.Text = "";
            }
        

        【讨论】:

        • 欢迎来到 StackOverflow。你知道这个问题在 3 年前就已经回答了吗?
        【解决方案5】:

        这个简单的代码足以在不使用 HTTP Handler 的情况下将图像插入 SQL

         protected void Page_Load(object sender, EventArgs e)
            {
                 if (!IsPostBack)
                    {
                        BindData();
                    }
                }
            private void BindData()
            {
                SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
                string strSQL = "Select * from table6";
                SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn);
                DataSet ds = new DataSet();
                dt.Fill(ds);
                grd1.DataSource = ds;
                grd1.DataBind();
                cn.Close();
            }
        protected void btn1_Click(object sender, EventArgs e)
            {
                if(fileupload.HasFile)
                {
        
                    string imageSrc = "~/Image/" +fileupload.PostedFile.FileName;
                 string ImageName = txt1.Text;
                SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
                cn.Open();
                string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')";
                SqlCommand cmd = new SqlCommand(strSql, cn);
                cmd.ExecuteNonQuery();
                cn.Close();
                BindData();
                txt1.Text = "";
            }
        

        【讨论】:

        • 这样可以防止 sql 注入吗?
        猜你喜欢
        • 2023-03-21
        • 1970-01-01
        • 2016-01-04
        • 2014-03-14
        • 2011-12-22
        • 1970-01-01
        • 2012-02-01
        • 2016-04-08
        • 1970-01-01
        相关资源
        最近更新 更多