简体   繁体   English

使用Angular 5反应性表单和ASP.NET Core Web API上传文件

[英]File Upload Using Angular 5 Reactive Form and ASP.NET Core Web API

I have a somewhat complex form with two nested FormGroup. 我有一个带有两个嵌套F​​ormGroup的复杂表单。 Each nested FormGroup containing a file input field along with other 6 input fields as Follows: 每个嵌套的FormGroup包含一个文件输入字段以及其他6个输入字段,如下所示:

In the Component: 在组件中:

updateEmployeeNomineeForm: FormGroup;

ngOnInit() {
   this.updateEmployeeNomineeForm = this.formBuilder.group({
      employeeNominee1: this.formBuilder.group({
        employeeId: [employeeId],
        nomineeName: [],
        nomineeRelation: [],
        nomineeContactNo: [],
        nomineeNationalId: [],
        nomineePicture: [], // This is the file input
        additionalInfo: []
      }),
      employeeNominee2: this.formBuilder.group({
        employeeId: [employeeId],
        nomineeName: [],
        nomineeRelation: [],
        nomineeContactNo: [],
        nomineeNationalId: [],
        nomineePicture: [], // This is the file input
        additionalInfo: []
      })
    });
  }

And the HTML form is as like as follows: HTML格式如下:

<div *ngIf="updateEmployeeNomineeForm">
    <form [formGroup]="updateEmployeeNomineeForm" (ngSubmit)="updateEmployeeNominees()">
      <div class="row">
        <div class="col-md-6">
          <div class="card">
            <div class="card-header">
              <strong>Nominee-1</strong>
            </div>
            <div formGroupName="employeeNominee1" class="card-body">

             //Other inputs omitted for Clarity

              <div class="form-group row">
                <label class="col-md-4 col-form-label">Nominee Picture</label>
                <div class="custom-file col-md-8">
                  <input type="file"  #nomineePicture1 formControlName="nomineePicture" class="form-control">
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-md-6">
          <div class="card">
            <div class="card-header">
              <strong>Nominee-2</strong>
            </div>
            <div formGroupName="employeeNominee2" class="card-body">

              //Other inputs omitted for Clarity

              <div class="form-group row">
                <label class="col-md-4 col-form-label">Nominee Picture</label>
                <div class="custom-file col-md-8">
                  <input type="file" #nomineePicture2 formControlName="nomineePicture" class="form-control">
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>
      <br />
      <div class="text-center">
        <button type="submit" [disabled]="!updateEmployeeNomineeForm.valid" class="btn btn-success text-white"><i class="fa fa-floppy-o" aria-hidden="true"></i> Submit</button>

    </form>

  </div>

Now the updateEmployeeNominees() method in the Component as follows: 现在,组件中的updateEmployeeNominees()方法如下:

updateEmployeeNominees(): void {
    this.employeeService.updateEmployeeNominees(this.updateEmployeeNomineeForm.value).subscribe((updateStatus) => {
      if (updateStatus) {
        this.resetUpdateEmployeeNominees();
        this.updateSuccessMessage = "Employee Nominees updated successfully!";
        setTimeout(() => {
          this.updateSuccessMessage = null;
        }, 4000);
      }
    }, (error) => {
      this.serverErrorMessage = this.errorMessageService.getServerErrorMessageText();
    });
  }

Now the updateEmployeeNominees() method in the EmployeeService as Follows: 现在updateEmployeeNominees()的EmployeeService方法如下:

updateEmployeeNominees(employeeNominees: any): Observable<any> {
    const body = JSON.stringify(employeeNominees);
    const headerOptions = new HttpHeaders({ 'Content-Type': 'application/json' });
    return this.http.put<any>(this.baseUrl + 'UpdateEmployeeNominees/'+ employeeId, body, {
      headers: headerOptions
    }).catch(this.handleError);
  }

In the ASP.NET Core Web Api Controller: 在ASP.NET Core Web Api控制器中:

[HttpPut("{id}")]
public async Task<IActionResult> UpdateEmployeeNominees([FromRoute] int id,[FromBody] EmployeeNomineesViewModel employeeNominees)
{
            //Necessary operation goes here
            return Ok(true);
}

Everything works as expected except the nomineePictures upload..Would anybody help me to bind the image files to the input field while posting the form to ASP.NET Web API controller method. 除了nomineePictures上传外,其他所有东西都按预期工作。在将表单发布到ASP.NET Web API控制器方法时,有人能帮我将图像文件绑定到输入字段吗?

you cannot get image directly.To get the image you have to some workaround.Add (change) event to input 您不能直接获取图像。要获取图像,您必须采取一些解决方法。添加(change)事件以进行输入

In your html 在你的html

<div class="custom-file col-md-8">
                  <input type="file" (change)="getfile($event)" formControlName="nomineePicture" class="form-control">
                </div>

In ts file ts文件中

public file: File;

getfile(e: any) {

  const fileList: FileList = e.target.files;
        this.file = fileList[0];

}

updateEmployeeNominees(): void {

console.log(this.file); // this will give you the file
console.log(this.updateEmployeeNomineeForm.value); this will give you formdata

}

Use the native browser FileReader to read the contents of a file. 使用本机浏览器FileReader读取文件的内容。 Heavy disclaimer: none of this code is tested, I just wrote it out of the hat in notepad. 严格的免责声明:此代码均未经过测试,我只是在记事本中脱口而出。 You should get the idea if copypaste doesn't work, and intellisense will help with the rest. 如果复制粘贴不起作用,您应该明白这一点,而intellisense将为您提供帮助。 ;D ; D

Template 模板

<input #fileInput type="file"/>

component.ts component.ts

@ViewChild('fileInput') fileInput: ElementRef;
get files() {
    return this.fileInput.nativeElement.files;
}
async submit() {
    if (!this.files.length) {
        console.error('Please select a file');
        return;
    }
    const fileContents = (await Promise.all(
        this.files.map(file => this.readFile(file))
    ).map(dataUrl => this.stripDataUrl(dataUrl));
    // Each item in FileContents is now a Base64 encoded string.
    // Post 'em to server and convert them there to a blob for saving as a file, or whatever you like.     
    // If you want to know the MIME type before posting, 
    // scrap that stripDataUrl() method and extract mime from the dataUrl.
    // DataUrls are formatted like 'data:image/png;base64,xxxxxxzzz'
}

/**
 *  @return a string without the encoding type and mime
 */
stripDataUrl(dataUrl) {
    return dataUrl.split(',')[1];
}

readFile(file) {
    return new Promise((resolve, reject) => {
        var reader = new FileReader();
        reader.onload = (e: any) => {
            resolve(e.target.result);
        };
        reader.readAsDataURL(file);
    });
}

You can also show a preview of a selected image: 您还可以显示所选图像的预览:

Template 模板

<img *ngIf="(thumb$|async); let thumb" [src]="thumb" class="thumbnail" />

component.ts component.ts

thumb$: Observable<string>;
ngOnInit() {
    this.thumb$ = Observable.fromEvent(this.fileInput.nativeElement, 'change')
        .filter(event => !!event.target.files.length)
        .switchMap(event => Observable.fromPromise(this.readFile(event.target.files[0])))
        .filter(dataUrl => /image/i.test(dataUrl));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从angular上传文件到asp.net核心web api controller - Upload file from angular to asp.net core web api controller 如何将文件从 Angular 上传到 ASP.NET Core Web API - How to Upload File from Angular to ASP.NET Core Web API 文件无法从 Angular 上传到 ASP.NET 核心 Web ZDB974238714CA8DE634A7CE1D083A1 - File failed to upload from Angular to ASP.NET Core Web API 使用 Asp.Net Core Web API 文件上传文件始终为空 - File upload using Asp.Net Core Web API file is always null 将文件从 angular 11 形式传递到 asp.net 核心 5 web Z8A5DA552ED12654E72Z3 的最佳方式是什么 - What is the best way pass file from angular 11 form to asp.net core 5 web api 使用(AngularJS 2)和ASP.net MVC Web API上传文件 - File Upload using (AngularJS 2) and ASP.net MVC Web API 如何在 ASP.net Core Web API 和 Angular 13 中上传图片 - How to upload pictures in ASP.net Core Web API and Angular 13 如何在Angular中实现CKEditor5并将图像上传到ASP.NET内核Web ZDB974238714CA8DE63FZACE? - How to implement CKEditor5 in Angular and upload image to ASP.NET Core Web API? 如何使用其他表单控件(Angular 8)和 asp.net 核心 api 上传图像 - How to upload image with other form control (Angular 8) and asp.net core api ASP.NET Core 2.0和Angular 4.3文件上传进度 - ASP.NET Core 2.0 and Angular 4.3 File Upload with progress
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM