title: File uploads to asp.net web api using pure javascript via ajax
body: <p>I am trying to do file uploads through <code>ajax</code> to my web api. My server side codes prove to be working cause I have managed to post files using a debugging Fiddler and it works fine. But I am failing to write successful javascript code that will be able to do the upload.</p>
  
  <p>Below is my html code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function sendImage() {
    var data = new FormData();
    var file = document.getElementById('upload').files[0];
  
    data.append("image",file);
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp_br=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
      xmlhttp_br=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp_br.onreadystatechange = function () {
      if (xmlhttp_br.readyState == 4 ) {
        var data = xmlhttp_br.responseText;
        alert(xmlhttp_br.status+" "+data);
        var file = JSON.parse(data);
      }
    }  
  
    xmlhttp_br.open("POST","http://localhost:59103/"+"api/upload/testUpload",true);
    xmlhttp_br.setRequestHeader("Content-Type","multipart/form-data");
    xmlhttp_br.setRequestHeader("filename", file.name);
    xmlhttp_br.send(data);
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input name="UploadedImage" id="upload" type="file"  accept="image/*"&gt;
  &lt;button onclick="sendImage()"&gt; Upload Image &lt;/button&gt;
  &lt;img id ="image"&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>My <code>c#</code> server side code is as follows</p>
  
  
  
  <pre><code>public async Task&lt;IHttpActionResult&gt; PostFile()
  {
    HttpRequestMessage request = this.Request;
    if (!request.Content.IsMimeMultipartContent())
    {
      throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }
  
    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);
    Stream img = null;
    string filename ="";
    foreach (var file in provider.Contents)
    {
      filename = file.Headers.ContentDisposition.FileName.Trim('\"');
      img = await file.ReadAsStreamAsync();
      //Do whatever you want with filename and its binaray data.
    }
  
    bool status = UploadFileToS3(filename, img, "edu-media");
  
    if (status)
    {
      return Ok();
    }
    else
    {
      return StatusCode(HttpStatusCode.ExpectationFailed);
    }
  }
  </code></pre>
  
  <p>Note that I am saving my files to <code>aws s3 buckets</code> and I don't want <code>jQuery</code>, only pure javascript.</p>