title: Storing upload file as binary data in SQL Server database
body: <p>I have been struggling with this issue. I'm trying to upload a file to the server and save it as binary data in the database.</p>
  
  <p>I know how to upload a file to the server and it's working fine.</p>
  
  <p>I need to know how to save the file as binary data in the database.</p>
  
  <p>This is what I have accomplished:</p>
  
  <p>In a SQL Server database, I have a table called <code>files</code> with the following columns:</p>
  
  <pre><code>Id, int, identity column 
  FileName, nvarchar(50) 
  UploadDate, datetime
  FileContent, varbinary(max)
  </code></pre>
  
  <p><code>HomeController.cs</code>:</p>
  
  <pre><code>[HttpPost]
  public ActionResult Index(HttpPostedFileBase[] files)
  {
      try
      {
          foreach (var file in files)
          {
              // extract only the filename
              var fileName = Path.GetFileName(file.FileName);
  
              // extract the file content to byte array
              var content = new byte[file.ContentLength];
              // reads the content from stream
              file.InputStream.Read(content, 0, file.ContentLength);
  
              //get file extesion
              var fileExtension = Path.GetExtension(fileName);
              //save file name as uniqe
              var uniqueFileName = Guid.NewGuid().ToString();
  
              Files fu = new Files
              {
                  FileName = uniqueFileName,
                  UploadDate = DateTime.Now,
                  FileContent = content
              };
  
              DB.Files.Add(fu);
              DB.SaveChanges();
          }
      }
      catch (Exception e) { }
  
      // redirect back to the index action to show the form once again
      return RedirectToAction("Index");
  }
  </code></pre>
  
  <p><code>index.cshtml</code>:</p>
  
  <pre><code>@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
  {
      &lt;input type="file" name="files" multiple/&gt;
      &lt;input type="submit" value="OK" /&gt;
  }
  </code></pre>
  
  <p>This code inserts a records into the database table, and the record looks like this:</p>
  
  <pre><code>Id  FileName                                UploadDate              FileContent
  1   716d30a5-8019-4ec9-a5e9-5b3966296bfc    2015-11-27 21:50:27.037 &lt;Binary data&gt;
  </code></pre>
  
  <p>I don't know why the <code>fileContent</code> column gets filled with the text <code>&lt;Binary data&gt;</code>.</p>