【问题标题】:Angular: get file path using reactive form(formbuilder)Angular:使用反应形式获取文件路径(formbuilder)
【发布时间】:2018-12-26 01:36:55
【问题描述】:

我正在学习从链接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>

【问题讨论】:

    标签: angular


    【解决方案1】:

    我不认为在响应式表单中以这种方式处理文件输入。理想情况下,您在 File Input 上收听 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]);
      }
    }
    

    这里有一个Working Sample StackBlitz 供您参考。

    【讨论】:

    • 在哪里写 onFileSelect() 方法。
    • 这将进入您的profile.component.ts 我已经添加了一个Working StackBlitz 例如。你可能想看看它。
    猜你喜欢
    • 2018-01-29
    • 2023-01-31
    • 1970-01-01
    • 2011-07-27
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    相关资源
    最近更新 更多