如何使用Web API和angular在表单提交中上传文件

时间:2018-06-25 04:36:35

标签: angular typescript asp.net-web-api angular6 angular-file-upload

我想在表单提交中上传文件,而不是在Web API上发布。

我想使用Web API将文件保存在本地物理路径中。

我收到此错误。

  

POST http://localhost:35257/api/Employee/Create 500(内部服务器   错误)。

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>

组件:

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

服务:

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

0 个答案:

没有答案