Angular:无法使用HttpPostedFileBase

时间:2018-06-27 13:19:40

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

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

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

在这里,我尝试使用FormData发送文件,并尝试使用HttpPostedFileBase在api调用中访问该文件,但它在给定的URL上发布(无错误)。

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();
   let fileBrowser = this.fileInput.nativeElement;
   frmData.append("myFile", fileBrowser.files[0]);

      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: employee, myFile: myFile }, {
  headers: {
    'Content-Type': undefined,
    'Accept': 'application/json'
  }
 });
 }

Web API:

  public int Create([FromBody] TblEmployee employee, HttpPostedFileBase myFile)
            {
             //code    
            }
     public partial class TblEmployee
        {
            public int EmployeeId { get; set; }
            public string Name { get; set; }              
        }

2 个答案:

答案 0 :(得分:0)

请勿添加Content-Type标头。让浏览器检测Content-Type并自行添加。

因此请在您的代码中将其注释掉

saveEmployee(employee, myFile): Observable<any> {
   return this._http.post(this.myAppUrl + 'api/Employee/Create', { employee: employee, myFile: myFile }, {
    headers: {
    //'Content-Type': undefined,
    'Accept': 'application/json'
    }
  });
}

答案 1 :(得分:0)

您应将所有数据放入FormData

const frmData = new FormData();
let fileBrowser = this.fileInput.nativeElement;
frmData.append("myFile", fileBrowser.files[0]);
frmData.append("employee", employee);

还有in API,您应该使用IFormFile

public IActionResult Create(string employee, IFormFile myFile)

更新 https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1

public class TblEmployee 
{
    // your employee info

    public IFormFile MyFile{ get; set; }
}
public async Task<IActionResult> Register(RegisterViewModel model)