title: Upload a File from HTML form using PostAsync
body: <p>I want to simply upload a file to server using WebAPI. I want to call the WebApi in my MVC HomeController. When I use the WebAPI directly it uploads files perfectly however when I want to call the WebAPI within my Controller using PostAsync, it does not send the file to the api for some reason.</p>
  
  <p>This is the action in my MVC Controller:</p>
  
  <pre><code> public async Task&lt;ActionResult&gt; Upload(HttpPostedFileBase upload)
      {
          ViewBag.Title = "Upload Files";
          if (upload != null &amp;&amp; upload.ContentLength &gt; 0)
          {
  
              var client = new HttpClient();
  
              string FullUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + ":" + Request.Url.Port + "/api/values";
              StringContent httpcontent = new StringContent(upload.FileName);
  
              var response = await client.PostAsync(FullUrl, httpcontent);
  
              var result = await response.Content.ReadAsAsync&lt;HttpResponseMessage&gt;();
  
          }
  
  
          return View();
      }
  </code></pre>
  
  <p>This is the .cshtml file:</p>
  
  <pre><code>&lt;form name="form1" method="post" action="/Home/Upload" enctype="multipart/form-data"&gt;
  
  &lt;div&gt;
      &lt;label for="upload"&gt;Choose a File&lt;/label&gt;
      &lt;input name="upload" type="file" /&gt;
  &lt;/div&gt;
  &lt;div&gt;
      &lt;input type="submit" value="Submit" /&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p></p>
  
  <p>Finally this is the WebApi Controller:</p>
  
  <pre><code> [HttpPost]
      public HttpResponseMessage PostFile()
      {
          HttpResponseMessage result = null;
          var httpRequest = HttpContext.Current.Request;
  
          if (httpRequest.Files.Count &gt; 0)
          {
              foreach (string file in httpRequest.Files)
              {
                  var postedFile = httpRequest.Files[file];
                  var filePath = HttpContext.Current.Server.MapPath("~/Files/" + postedFile.FileName);
                  postedFile.SaveAs(filePath);
              }
              result = Request.CreateResponse(HttpStatusCode.Created);
          }
          else
          {
              result = Request.CreateResponse(HttpStatusCode.BadRequest);
          }
  
          return result;
      }
  </code></pre>