Ishara Sandun
Ishara Sandun

Reputation: 737

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

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]

Upvotes: 3

Views: 5373

Answers (3)

Elialber Lopes
Elialber Lopes

Reputation: 663

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

Upvotes: 2

Shaip Zejnullahu
Shaip Zejnullahu

Reputation: 9

This works for me: component.html:

<input type="file" id="file" (change)="handleFileInput($event.target.files)">

Interface

export interface UploadDoc {
LlojiKampanjesId: number;
FileToUpload: File; }

component.ts

listToUpload: UploadDoc = {LlojiKampanjesId:0, FileToUpload:null};
handleFileInput(files: FileList) {
this.listToUpload.FileToUpload = files.item(0);}
public uploadList() {
this.disableSubmit = true;
this.rastetService.uploadFile(this.listToUpload, this.userInfo.Token).subscribe((result: string) => {
    this.thisDialogRef.close('close');
    this.disableSubmit = false;
  },
    error => {
      if (error instanceof HttpErrorResponse) {

      } 
      else {           
      }
      this.spinnerService.hide();
      this.disableSubmit = false;
    });}

service.ts

uploadFile (listToUpload:UploadDoc,token: string ) {
let headers= new HttpHeaders({'Authorization':'Bearer ' + token});  
const formData: FormData = new FormData();
formData.append('UploadDoc', listToUpload.FileToUpload, listToUpload.FileToUpload.name);
return this.$http
  .post(this.endpointUploadFile, formData, {headers:headers})}

web api:

[System.Web.Http.HttpPost]
    public HttpResponseMessage UploadList()
    {
        HttpResponseMessage response = new HttpResponseMessage();
        var httpRequest = HttpContext.Current.Request;
        //
        //  -----------------
        //

        return response;
    }

Upvotes: 0

alec
alec

Reputation: 396

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

Upvotes: 0

Related Questions