我想在表单提交上上传文件,但不发布在Web API上。
并使用Web API将文件保存在本地物理路径中。
在这里,我尝试使用FormData发送文件,并尝试使用HttpContext.Current.Request.Files在api调用中访问该文件,但计数为0。
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>
组件:
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)
}
服务:
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; }
}
我正在跟踪this链接。