1

I want to upload a file on form submit, but its not posting on web API.

And save file in a local physical path using Web API.

Here I am trying to send file using FormData and trying to access the same in api call using HttpContext.Current.Request.Files but its giving 0 count.

Html :

<form [formGroup]="employeeForm" (ngSubmit)="save()" #formDir="ngForm" novalidate style="position:relative;" enctype="multipart/form-data">
  <div>
 <input class="form-control" type="text" formControlName="Name">
        <input type="file" id="FileUploader" (change)="onFileChange($event)" #fileInput accept=".pdf,.doc,.docx,.png">
        <button type="button" class="btn btn-sm btn-default" (click)="clearFile()">clear file</button>
      </div>
</form>

Component :

myFiles: string[] = [];
  form: FormGroup;
  loading: boolean = false;
  @ViewChild('fileInput') fileInput: ElementRef;

onFileChange(e) {        
  for (var i = 0; i < e.target.files.length; i++) {
    this.myFiles.push(e.target.files[i]);
   } 
  }
save() {
   const frmData = new FormData();
  for (var i = 0; i < this.myFiles.length; i++) {
    frmData.append("fileUpload", this.myFiles[i]);
  }
      this._employeeService.saveEmployee(this.employeeForm.value, frmData)
        .subscribe((data) => {
          this._router.navigate(['/fetch-employee']);
        }, error => this.errorMessage = error)
    }

Service :

saveEmployee(employee, myFile): Observable<any> {
    return this._http.post(this.myAppUrl + 'api/Employee/Create', employee, myFile);   
  }

Web API :

 public int Create([FromBody] TblEmployee employee)
            {
System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;    
            // CHECK THE FILE COUNT.
            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];    
                if (hpf.ContentLength > 0)
                {
                    // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                    if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                    {
                        // SAVE THE FILES IN THE FOLDER.
                        hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        iUploadedCnt = iUploadedCnt + 1;
                    }
                }
            }
                return objemployee.AddEmployee(employee, myFile);
            }
     public partial class TblEmployee
        {
            public int EmployeeId { get; set; }
            public string Name { get; set; }              
        }

I am following this link.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.