title: HTTP POST using XHR with Chunked Transfer Encoding
body: <p>I have a REST API that accepts an Audio file via an HTTP Post.  The API has support for Transfer-Encoding: chunked request header so that the file can be uploaded in pieces as it is being created from a recorder running on the client.  This way the server can start processing the file as it arrives for improved performance.  For example:</p>
  
  <blockquote>
    <p>HTTP 1.1 POST .../v1/processAudio</p>
    
    <p>Transfer-Encoding: chunked</p>
    
    <p>[Chunk 1 256 Bytes] (server starts processing when arrives)</p>
    
    <p>[Chunk 2 256 Bytes]</p>
    
    <p>[Chunk 3 256 Bytes]</p>
    
    <p>...</p>
  </blockquote>
  
  <p>The audio files are typically short and are around 10K to 100K in size.  I have C# and Java code that is working so I know that API works.  However, I cannot seem to get the recording and upload working in a browser using javascript.</p>
  
  <p>Here is my Test Code that does a POST to localhost with Transfer-Encoding:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt;
  &lt;script type="text/javascript"&gt;
    function streamUpload() {
      var blob = new Blob(['GmnQPBU+nyRGER4JPAW4DjDQC19D']);
      var xhr = new XMLHttpRequest();
      // Add any event handlers here...
      xhr.open('POST', '/', true);
      xhr.setRequestHeader("Transfer-Encoding", "chunked");
      xhr.send(blob);
    }
  &lt;/script&gt;
  
  &lt;body&gt;
    &lt;div id='demo'&gt;Test Chunked Upload using XHR&lt;/div&gt;
    &lt;button onclick="streamUpload()"&gt;Start Upload&lt;/button&gt;
  &lt;/body&gt;
  
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>The problem is that i'm receiving the following Error in Chrome</p>
  
  <p>Refused to set unsafe header "Transfer-Encoding"</p>
  
  <p>streamUpload @ uploadTest.html:14
  onclick @ uploadTest.html:24</p>
  
  <p>After looking at XHR documentation i'm still confused because it does not talk about unsafe request headers.  I'm wondering if its possible that XHR does not allow or implement <em>Transfer-Encoding: chunked</em> for HTTP POST?  </p>
  
  <p>I've looked at work arounds using multiple XHR.send() requests and WebSockets but both are undesirable because it will require significant changes to the server APIs which are already in place, simple, stable and working.  The only issue is that we cannot seem to POST from a browser with psedo-streaming via Transfer-Encoding: chunked request header.</p>
  
  <p>Any thoughts or advice would be very helpful.</p>