Angular:使用响应式(Reactive)表单(formbuilder)获取文件路径

标签 angular

我正在学习从链接 https://angular.io/guide/reactive-forms 获取表单值。但那里没有给出文件上传,所以我修改了代码并在表单和组件中添加了文件上传选项,但没有获取路径。我得到的输出是

{
  "firstName": "p",
  "lastName": "a",
  "photo": "C:\\fakepath\\gorgeous-wallpapers-hd-for-desktop-6.jpg"
}

在此我得到了不正确的照片路径。

profile.component.ts

import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile.component.html',
  styleUrls: []
})
export class ProfileEditorComponent {
  profileForm = this.fb.group({
    firstName: [''],
    lastName: [''],
    photo: ['']
  });

  constructor(private fb: FormBuilder) {}
  public obj: any;

  updateProfile() {
    this.obj = this.profileForm.value;
  }
}

profile.component.html

<p>
  Form Status: {{obj|json}}
</p>
<div class="row">
  <div class="col-md-4 col-md-offset-4">
    <form [formGroup]="profileForm">
      <div class="form-group">
        <label> First Name:</label>
        <input type="text" class="form-control" formControlName="firstName">
      </div>

      <div class="form-group">
        <label>Last Name:</label>
        <input type="text" class="form-control" formControlName="lastName">
      </div>

      <div class="form-group">
        <label>Upload File:</label>
        <input type="file" class="form-control" formControlName="photo">
      </div>

      <div class="form-group">
        <button class="btn btn-primary" (click)="updateProfile()">Update Name</button>
      </div>

    </form>
  </div>

</div>

最佳答案

我不认为文件输入在响应式表单中是这样处理的。理想情况下,您会监听文件输入上的 change 事件,然后将其上传到服务器并从那里获取下载 URL。或者将其转换为 Base64 字符串。

然后您可以将其添加到您收到的作为表单值的对象。

要将图像转换为 Base64,您可以执行以下操作:

...
<div class="row">
  <div class="col-md-4 col-md-offset-4">
    <form [formGroup]="profileForm">
      ...
      <div class="form-group">
        <label>Upload File:</label>
        <input 
          (change)="onFileSelect($event.target)" 
          type="file" 
          class="form-control">
      </div>
      ...
    </form>
  </div>
</div>

并实现 onFileSelect($event) 方法,如下所示:

onFileSelect(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = (e: any) => {
      this.photoUrl = e.target.result;
    }
    reader.readAsDataURL(input.files[0]);
  }
}

Here's a Working Sample StackBlitz for your ref.

关于Angular:使用响应式(Reactive)表单(formbuilder)获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53924253/

相关文章:

angular - 参数化 ngrx 选择器的方法有什么区别

Angular 路由器导出失败,routerLink 位于 AppComponent 之外

angular - 类型 'switchMap' 上不存在属性 'Observable<User>'

angular - RxJs 扩展和延迟运算符未按预期工作

angular - 如何从 Angular 事件监听器访问全局变量

angular2 构建问题 useFactory 与功能

javascript - 如何使用 Angular 根据在html中选择的单选按钮获取 bool 值

ios - Nativescript 插件在 Podfile 中指定 Pod 版本

css - Angular Material : override css table inside a mat-menu

angular - 使用 Http 和 DataSource 的 Material 2 分页