Asp.Net将图像添加到SQL表...我做错了什么?

Asp.Net将图像添加到SQL表...我做错了什么?

问题描述:

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

PROFILEGALLERY表包含:

用户ID为nvarchar(50)
标题为nvarchar(10)
OriginalImage VARBINARY(最大值)
ThumbImage VARBINARY(最大值)

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(); 
} 

您应该使用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(); 
    } 
} 
+0

谢谢!你真棒!哇,这是一个头痛的问题。我甚至不在乎为什么我的方式不起作用。现在我知道为什么每个人都这样做。谢谢! – user84786 2009-04-08 13:16:35

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

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

看看你的代码,我有点担心你对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 []

我有点震惊,你可以添加一个字节数组到一个字符串,特别是sicne它只是给了我们这个类型的名字。

+0

哈哈,非常真实。谢谢! – user84786 2009-04-08 13:23:25

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 = ""; 
    } 
+0

欢迎来到StackOverflow。你知道这个问题已经在3年前回答了吗? – RichardTheKiwi 2012-10-19 21:20:56

这个简单的代码就足以插入图像到SQL没有考虑HTTP处理程序

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 = ""; 
    } 
+0

这是否可以防止SQL注入? – Leigh 2012-10-19 21:44:29