0

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

I want to save file in a local physical path using Web API.

I am getting this error.

POST http://localhost:35257/api/Employee/Create 500 (Internal Server Error).

Html :

<form [formGroup]="employeeForm" (ngSubmit)="save()" #formDir="ngForm" novalidate style="position:relative;">
  <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 :

public myFile?: any;
  form: FormGroup;
  loading: boolean = false;
  @ViewChild('fileInput') fileInput: ElementRef;

onFileChange(event) { 
    if (event.target.files.length > 0) {
      let file = this.myFile= event.target.files[0];
      this.employeeForm.get('FileUploader').setValue(file);
    }   
  }
save() {       
      this._employeeService.saveEmployee(this.employeeForm.value, this.myFile)
        .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, HttpPostedFileBase myFile)
        {
            return objemployee.AddEmployee(employee, myFile);
        }
 public partial class TblEmployee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }                
    }
5
  • Your code seem pretty cool but some thing is not working with your api. have you tried to call your api using external tool like postman? Commented Jun 25, 2018 at 4:56
  • Just try below code in your sevice: saveEmployee(employee, myFile): Observable<any> { return this._http.post(this.myAppUrl + 'api/Employee/Create', {employee:employee,myFile:myFile}); } Commented Jun 25, 2018 at 4:58
  • same server error, its unable to convert myFile to HttpPostedFileBase type .. Commented Jun 25, 2018 at 5:10
  • where you define employeeForm variable? Commented Jun 25, 2018 at 6:14
  • in constructor using formbuilder :- this.employeeForm = this._fb.group({ EmployeeId: 0, Name: ['', [Validators.required]] }); Commented Jun 25, 2018 at 6:24

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.