title: Uploading/Downloading Byte Arrays with AngularJS and ASP.NET Web API
body: <p>I have spent several days researching and working on a solution for uploading/downloading byte[]’s. I am close, but have one remaining issue that appears to be in my AngularJS code block.</p>
  
  <p>There is a similar question on SO, but it has no responses. See <a href="https://stackoverflow.com/questions/23849665/web-api-accept-and-post-byte-array">https://stackoverflow.com/questions/23849665/web-api-accept-and-post-byte-array</a> </p>
  
  <p>Here is some background information to set the context before I state my problem.</p>
  
  <ol>
  <li>I am attempting to create a general purpose client/server interface to upload and download byte[]’s, which are used as part of a proprietary server database. </li>
  <li>I am using TypeScript, AngularJS, JavaScript, and Bootstrap CSS on the client to create a single page app (SPA).</li>
  <li>I am using ASP.NET Web API/C# on the server.</li>
  </ol>
  
  <p>The SPA is being developed to replace an existing product that was developed in Silverlight so it is constrained to existing system requirements. The SPA also needs to target a broad range of devices (mobile to desktop) and major OSs.</p>
  
  <p>With the help of several online resources (listed below), I have gotten most of my code working. I am using an asynchronous multimedia formatter for byte[]’s from the Byte Rot link below.</p>
  
  <p><a href="http://byterot.blogspot.com/2012/04/aspnet-web-api-series-part-5.html" rel="nofollow noreferrer">http://byterot.blogspot.com/2012/04/aspnet-web-api-series-part-5.html</a>   </p>
  
  <p><a href="https://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api">Returning binary file from controller in ASP.NET Web API</a></p>
  
  <ol>
  <li>I am using a jpeg converted to a Uint8Array as my test case on the client. </li>
  <li>The actual system byte arrays will contain mixed content compacted into predefined data packets. However, I need to be able to handle any valid byte array so an image is a valid test case.</li>
  <li>The data is transmitted to the server correctly using the client and server code shown below AND the Byte Rot Formatter (NOT shown but available on their website).</li>
  <li>I have verified that the jpeg is received properly on the server as a byte[] along with the string parameter metadata.</li>
  <li>I have used Fiddler to verify that the correct response is sent back to the client. 
  
  <ul>
  <li>The size is correct</li>
  <li>The image is viewable in Fiddler.</li>
  </ul></li>
  <li><p><strong>My problem is that the server response in the Angular client code shown below is not correct.</strong></p>
  
  <ul>
  <li><em>By incorrect</em>, I mean the <strong>wrong size (~10K versus ~27.5K)</strong> and it is <strong>not recognized as a valid value for the UintArray constructor</strong>. Visual Studio shows JFIF when I place the cursor over the returned “response” shown in the client code below, but there is no other visible indicator of the content.</li>
  </ul></li>
  </ol>
  
  <p>/**********************   Server Code ************************/
  <strong>Added missing item to code after [FromBody]byte[]</strong></p>
  
  <pre><code>public class ItemUploadController : ApiController{ 
  [AcceptVerbs("Post")]
      public HttpResponseMessage Upload(string var1, string var2, [FromBody]byte[] item){
          HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
          var stream = new MemoryStream(item);
          result.Content = new StreamContent(stream);
          result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
          return result;
      }
  }
  </code></pre>
  
  <p>/***************** Example Client Code  ********************/</p>
  
  <p>The only thing that I have omitted from the code are the actual variable parameters.</p>
  
  <pre><code>$http({
  url: 'api/ItemUpload/Upload',
      method: 'POST',
      headers: { 'Content-Type': 'application/octet-stream' },// Added per Byte Rot blog...
      params: {
          // Other params here, including string metadata about uploads
          var1: var1,
          var2: var2
      },
  data: new Uint8Array(item),
  // arrybuffer must be lowecase. Once changed, it fixed my problem.
  responseType: 'arraybuffer',// Added per http://www.html5rocks.com/en/tutorials/file/xhr2/
  transformRequest: [],
  })
  .success((response, status) =&gt; {
      if (status === 200) {
          // The response variable length is about 10K, whereas the correct Fiddler size is ~27.5K.
          // The error that I receive here is that the constructor argument in invalid.
          // My guess is that I am doing something incorrectly with the AngularJS code, but I
          // have implemented everything that I have read about. Any thoughts???
          var unsigned8Int = new Uint8Array(response);
          // For the test case, I want to convert the byte array back to a base64 encoded string
          // before verifying with the original source that was used to generate the byte[] upload.
          var b64Encoded = btoa(String.fromCharCode.apply(null, unsigned8Int));
          callback(b64Encoded);
      }
  })
  .error((data, status) =&gt; {
      console.log('[ERROR] Status Code:' + status);
  });
  </code></pre>
  
  <p>/****************************************************************/</p>
  
  <p>Any help or suggestions would be greatly appreciated.</p>
  
  <p>Thanks...</p>
  
  <p><strong>Edited to include more diagnostic data</strong></p>
  
  <p>First, I used the angular.isArray function to determine that the response value is NOT an array, which I think it should be.</p>
  
  <p>Second, I used the following code to interrogate the response, which appears to be an invisible string. The leading characters do not seem to correspond to any valid sequence in the image byte array code.</p>
  
  <pre><code>var buffer = new ArrayBuffer(response.length);
  var data = new Uint8Array(buffer);
  var len = data.length, i;
  for (i = 0; i &lt; len; i++) {
      data[i] = response[i].charCodeAt(0);
  }
  </code></pre>
  
  <p><strong>Experiment Results</strong></p>
  
  <p>I ran an experiment by creating byte array values from 0 - 255 on the server, which I downloaded. The AngularJS client received the first 128 bytes correctly (i.e., 0,1,...,126,127), but the remaining values were 65535 in Internet Explorer 11, and 65533 in Chrome and Firefox. Fiddler shows that 256 values were sent over the network, but there are only 217 characters received in the AngularJS client code. If I only use 0-127 as the server values, everything seems to work. I have no idea what can cause this, but the client response seems more in line with signed bytes, which I do not think is possible.</p>
  
  <p>Fiddler Hex data from the server shows 256 bytes with the values ranging from 00,01,...,EF,FF, which is correct. As I mentioned earlier, I can return an image and view it properly in Fiddler, so the Web API server interface works for both POST and GET.</p>
  
  <p>I am trying vanilla XMLHttpRequest to see I can get that working outside of the AngularJS environment.</p>
  
  <p><strong>XMLHttpRequest Testing Update</strong></p>
  
  <p>I have been able to confirm that vanilla XMLHttpRequest works with the server for the GET and is able to return the correct byte codes and the test image. </p>
  
  <p>The good news is that I can hack around AngularJS to get my system working, but the bad news is that I do not like doing this. I would prefer to stay with Angular for all my client-side server communication.</p>
  
  <p>I am going to open up a separate issue on Stack Overflow that only deals with the GET byte[] issues that I am have with AngularJS. If I can get a resolution, I will update this issue with the solution for historical purposes to help others.</p>
  
  <p><strong>Update</strong></p>
  
  <p>Eric Eslinger on Google Groups sent me a small code segment highlighting that responseType should be "arraybuffer", all lower case. I updated the code block above to show the lowercase value and added a note. </p>
  
  <p>Thanks...</p>