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

时间:2009-04-08 12:55:49

标签: c# asp.net sql image insert

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

PROFILEGALLERY TABLE CONTAINS:

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

5 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

只是看看你的代码,我有点担心你对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它只是给我们类型的名称。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

这个简单的代码足以将图像插入SQL而无需使用HTTP Handler

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