title: Upload to database in asp.net
body: <p>I am trying to upload files to database but it is giving me an null exception error</p>
  
  <p>Here is the error:
  System.NullReferenceException: Object reference not set to an instance of an object.</p>
  
  <p>Can anybody help me finding the error:</p>
  
  <p>Here is aspx code</p>
  
  <pre><code>&lt;div&gt;
      &lt;asp:FileUpload ID="FileUpload1" runat="server" /&gt;
  &lt;asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" /&gt;
  &lt;hr /&gt;
  &lt;asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
      RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
      AutoGenerateColumns="false"&gt;
      &lt;Columns&gt;
          &lt;asp:BoundField DataField="Name" HeaderText="File Name"/&gt;
          &lt;asp:TemplateField ItemStyle-HorizontalAlign = "Center"&gt;
  
          &lt;/asp:TemplateField&gt;
      &lt;/Columns&gt;
  &lt;/asp:GridView&gt;
      &lt;/div&gt;
  </code></pre>
  
  <p>Here is the code behind:</p>
  
  <pre><code>using System;
  using System.IO;
  using System.Data;
  using System.Data.SqlClient;
  using System.Configuration;
  
  public partial class DatabaseDownload : System.Web.UI.Page
  {
      protected void Page_Load(object sender, EventArgs e)
      {
  
      }
      protected void Upload(object sender, EventArgs e)
      {
          string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
          string contentType = FileUpload1.PostedFile.ContentType;
          using (Stream fs = FileUpload1.PostedFile.InputStream)
          {
              using (BinaryReader br = new BinaryReader(fs))
              {
                  byte[] bytes = br.ReadBytes((Int32)fs.Length);
                  string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                  using (SqlConnection con = new SqlConnection(constr))
                  {
                      string query = "insert into tblFiles values (@Name, @ContentType, @Data)";
                      using (SqlCommand cmd = new SqlCommand(query))
                      {
                          cmd.Connection = con;
                          cmd.Parameters.AddWithValue("@Name", filename);
                          cmd.Parameters.AddWithValue("@ContentType", contentType);
                          cmd.Parameters.AddWithValue("@Data", bytes);
                          con.Open();
                          cmd.ExecuteNonQuery();
                          con.Close();
                      }
                  }
              }
          }
          Response.Redirect(Request.Url.AbsoluteUri);
      }
  }
  </code></pre>