Search code examples
c#sqlasp.netvarbinary

Use varbinary to retrieve image to database using FileUpload


Okay so I'm using adding it to the database by using

  HttpPostedFile postedFile = eventImage.PostedFile;
        string fileExtension = Path.GetExtension(postedFile.FileName);

        if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".png")
        {
            Stream stream = postedFile.InputStream;
            BinaryReader reader = new BinaryReader(stream);
            byte[] imgByte = reader.ReadBytes((int)stream.Length);
            con = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-StudentMoneySaver-20160203040444.mdf;Initial Catalog=aspnet-StudentMoneySaver-20160203040444;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("insert into Events (AspNetUsersId,EvtName,EvtType,EvtDescription,EvtDate,EvtVote, EvtImage) values (@AspNetUsersId, @EvtName, @EvtType, @EvtDescription, @EvtDate, @EvtVote, @EvtImage)", con);

            cmd.Parameters.AddWithValue("@AspNetUsersId", userId);
            cmd.Parameters.AddWithValue("@EvtName", eventName.Text);
            cmd.Parameters.AddWithValue("@EvtType", eventType.Text);
            cmd.Parameters.AddWithValue("@EvtDescription", eventDescription.Text);
            cmd.Parameters.AddWithValue("@EvtDate", datetimepicker.Value);
            cmd.Parameters.AddWithValue("@EvtVote", 0);
            cmd.Parameters.Add("@EvtImage", SqlDbType.VarBinary).Value = imgByte;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

and trying to call just the image by using

  byte[] imgByte = null;
        con = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-StudentMoneySaver-20160203040444.mdf;Initial Catalog=aspnet-StudentMoneySaver-20160203040444;Integrated Security=True");
        SqlCommand cmd = new SqlCommand("SELECT * FROM Events", con);
        con.Open();
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            string str = Convert.ToBase64String(imgByte);
            imageTest.Src = "data:Image/png;base64," + str;
        }

with the front end code being

<img runat="server" id="imageTest" src="imageIDtagName" />

I'm getting the error message "Value cannot be null. Parameter name: inArray

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: inArray" I think I'm close!

Events Table


Solution

  • If you want to load Image from SQL you do it like this:

    byte[] imgByte = null;
    
    SqlCommand cmd = new SqlCommand("SELECT Image FROM tableName",yourConnectionStringHere);
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.fill(ds);
    foreach(DataRow dr in ds.Tables[0].Rows)
    {
      imgByte = (byte[])(dr["ImageColumnNameHere"].ToString());
      string str = Convert.ToBase64String(imgByte);
      imageIDtagName.Src = "data:Image/png;base64," + str;
    }
    

    Saving Image using the File Upload is done like this:

    HttpPostedFile postedFile = imgFile.PostedFile;
    string fileExtension = Path.GetExtension(postedFile.FileName);
    
     if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".png")
     {
                Stream stream = postedFile.InputStream;
                BinaryReader reader = new BinaryReader(stream);
                byte[] imgByte = reader.ReadBytes((int)stream.Length);
         SqlCommand cmd = new Sqlcommand("INSERT INTO tableName(Image) VALUES(@img)",yourConnectionStringHere);
    cmd.Parameters.Add("@img",SqlDbType.VarBinary).Value = imgByte;
         cmd.ExecuteNonQuery();
     }
    

    P.S. Surround your sqlconnection with using statement like

    using(SqlConnection con = new SqlConnection(""))
    {
       //your code here
    }
    

    to save you from doing the con.Open() and con.Close()

    Edited: To access src property of your html tags, just add runat="server" in your html tag.