how to upload a file on form submit using web api and angular

为君一笑 提交于 2019-12-25 03:07:57

问题


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; }                
    }

来源:https://stackoverflow.com/questions/51016370/how-to-upload-a-file-on-form-submit-using-web-api-and-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!