title: Updating 'hidden' binary data in ASP.NET MVC on HTML5 'drop' event
body: <p>I need to figure out how to base64 encode the response from an HTML5 FileReader ...</p>
  
  <p>Here's the problem - I've added a 'drop' event listener on a div so you can drag-n-drop an image file on to my page ... this is an ASP.NET MVC3 Razor form which has an @html.HiddenFor(...) field which contains a byte array which represents an image ...</p>
  
  <p>If the user drops a file on to my div, then I want to update the 'value' of my hidden input field.</p>
  
  <p>My client-side drop handler looks a bit like this:</p>
  
  <pre><code>dropArea.addEventListener("drop", function (evt) {
  
      var draggedFiles = evt.dataTransfer.files;
  
      if (typeof (draggedFiles) != "undefined") {
          xhr = new XMLHttpRequest();
  
          xhr.onreadystatechange = function () {
              if (xhr.readyState == 4) {
                  var reader = new FileReader();
  
                  reader.onload = (function (theFile) {
                      return function (e) {
                          var hiddenInput = document.getElementById("myMvcHiddenInputField");
                          hiddenInput.value = base64.encode(e.target.result);
                      };
                  })(draggedFiles[0]);
  
                  reader.readAsBinaryString(draggedFiles[0]);
              }
          }
  
          xhr.open("post", "/MyController/SetTempImage", true);
  
          xhr.setRequestHeader("Content-Type", "multipart/form-data");
          xhr.setRequestHeader("X-File-Name", draggedFiles[0].fileName);
          xhr.setRequestHeader("X-File-Size", draggedFiles[0].fileSize);
          xhr.setRequestHeader("X-File-Type", draggedFiles[0].type);
  
          xhr.send(draggedFiles[0]);
  
          evt.preventDefault();
          evt.stopPropagation();
      }
  }, false);
  </code></pre>
  
  <p>... the problem lies in how I'm handling the response from the FileReader ... I need to re-encode the results in a way that ASP.NET is expecting the hidden field (base64.encode is a jquery library I downloaded ... I'm pretty sure it's not what I need here, as I don't think it is designed to cope with encoding binary data)</p>
  
  <p>I guess my question is, when updating 'hidden' byte arrays in MVC pages, how do I encode file data on the client so that it can re-integrate with my model data when it's posted back to the server?</p>
  
  <p>... It's late ... I suspect that sounds like gibberish ... but if anyone can make sense of my problem, your help would be greatly appreciated.</p>