title: How to upload files to a Web API server and send parameters along to the action?
body: <p>Good day!</p>
  
  <p>I am working on a ASP.NET Web API 2 project. At a certain point there is a need to upload some files. The files need to be linked to a certain FileModel (our own class). So, the client needs to send IEnumerable as parameter and the files as content. Because it's a RESTful API, both have to be sent in the same request.</p>
  
  <p>The best we could come up with is the follow Controller action: </p>
  
  <pre><code>public async Task&lt;HttpResponseMessage&gt; Add([FromUri] IEnumerable&lt;FileModel&gt; fileModels)
  {
     // REQUEST INTEGRITY TESTING
  
     var streamProvider = new CustomMultipartFormDataStreamProvider(fileSavePath, fileModels);
     // Read the MIME multipart content using the stream provider we just created.
     var work = await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(async t =&gt;
          {
              // SOME WORK DONE AFTER SAVING THE FILES TO THE HARD DRIVE
          }
  
  }
  </code></pre>
  
  <p>The problem is following: the files are being uploaded with a 'multipart/form-data' Content-Type header. <strong>We need to know the contents of the FileModels before manipulating the files on the server side. If we use the MultipartFormDataStreamProvider, we can only access the non file parameters after the files have already been saved to the hard drive.</strong></p>
  
  <p>The only workaround for this we could find is to send the IEnumerable&lt; FileModel > parameter in the URL. But given that the URL has a limited max length, this is not a reliable method. </p>
  
  <p><strong>The question is</strong>: Is there a way to submit both the IEnumerable&lt; FileModel > fileModels parameter and the files <strong>in the body of the request</strong> and get access to the fileModels parameter before accessing the files? We also want to be able to use HttpContext.Current.Request.Files.Count; </p>
  
  <p>Our current jQuery for file upload looks like this (for early testing purposes, it only supports one file upload):</p>
  
  <pre><code>$('#Upload').click(function(e) {
              e.preventDefault();
  
              var headers = new Array();
              headers["SessionId"] = sessionId;
  
              var files = $('#fileInput').get(0).files;
              var formData = new FormData();
              formData.append("files", files[0]);
  
              var fileModel = $('#fileSubmission').serialize();
  
              $.ajax({
                  url: "api/Submissions/Add/?" + fileModel,
                  headers: headers,
                  type: 'POST',
                  data: formData,
                  cache: false,
                  contentType: false,
                  processData: false,
                  dataType: 'json'
              });
          });
  </code></pre>
  
  <p>Thank you very much! </p>