Angular : Unable to upload file using web API

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 05:22:41

问题


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.

来源:https://stackoverflow.com/questions/51021454/angular-unable-to-upload-file-using-web-api

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