file count is always zero in web API when trying to upload a document with angular 2

Viewed 4780

I'am trying to upload a file using a web API in C#. For that the code I have used in as follows. httpRequest.Files.Count value always gets zero when i'm trying to upload a document. What am I doing wrong?

mcDocuments.ts file

fileChange(event) {
  debugger;
  let fileList: FileList = event.target.files;
  if (fileList.length > 0) {
    let file: File = fileList[0];
    let formData: FormData = new FormData();
    formData.append('uploadFile', file, file.name);
    let token = JSON.parse(Cookie.get('currentUser')).token
    let headers = new Headers();
    headers.append('Access-Control-Allow-Origin', '*');

    headers.append('Authorization', 'bearer ' + token);

    headers.append('UserName',
      JSON.parse(Cookie.get('currentUser')).username);
    headers.append('Content-Type', 'multipart/form-data');

    let options = new RequestOptions({ headers: headers });
    let apiUrl1 = "http://localhost:53732/api/UploadFileApi";
    this.http.post(apiUrl1, formData, options)
      .map(res => res.json())
      .catch(error => Observable.throw(error))
      .subscribe(
      data => console.log('success'),
      error => console.log(error)
      )
  }
  window.location.reload();
}

mcDocuments.html file

  <input type="file" id="btnUpload" value="Upload" (change)="fileChange($event)" class="upload" /> 

web Api

  using System.Net.Http;
  using System.Web;
  using System.Web.Http;
  namespace FileUpload_WebAPI_Angular2.Controllers
  {
  public class UploadFileApiController : ApiController
  {
    [HttpPost]
    public HttpResponseMessage UploadJsonFile()
    {
        HttpResponseMessage response = new HttpResponseMessage();
        var httpRequest = HttpContext.Current.Request;

        if (httpRequest.Files.Count > 0)
        {
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var filePath = 
                HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
                postedFile.SaveAs(filePath);
            }
           }
        return response;
       }
     }
   }

module.ts file

   declarations: [    McDocumentsComponent,],
   providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
   bootstrap: [McDocumentsComponent]
3 Answers

Check if your inteceptor class set a content-type. If so, remove it.

Try using Request.Files or Request.Form.Files instead of HttpContext.Current.Request.Files. A similar issue was experienced here: Request.Files is always null

Related