Asp.Net Adding Images to SQL Table…What am I doing

2019-09-02 06:55发布

问题:

I have done this previously but in a different way. I am trying to get the code below to work. If I do not cast 'OriginalPhoto' or 'Thumbnail' an error occurs. Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. I don't understand why it asking to cast. However if I do cast it, the images add to the database just fine in a binary data format. When trying to view the images, i get the error 'Unable to display the given data'. I have inserted both byte[] into a table using a SqlDataAdapter and that works. I want to use this method though, what am I doing wrong?

PROFILEGALLERY TABLE CONTAINS:

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

回答1:

You should use sql parameters:

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:

Don't try to build the data into the insert query. Try this:

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:

Just looking at your code, I'm a little concerned that you are wide open for a SQL Injection attack. To help mitigate this should also fix your problem. You need to use a parametized query. Something like

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

The reason your code is failing can be seen with this sample application:

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

This outputs This is my byte array: System.Byte[]

I'm a little shocked that you can add a byte array to a string, especially sicne it just gives us the name of the type.



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


回答5:

This simple code is enough to insert images to SQL without taking 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 = "";
    }