javascript - 文件上传控件响应式(Reactive)表单

标签 javascript angular

问题

我目前有一个包含许多字段的表单,其中一个是文件上传字段。它们都构成了在我的构造函数中声明的 FormGroup 的一部分。现在,我可以使用 this.control.value 访问除文件控件之外的所有文本控件。当我尝试访问文件的表单控件的 value 时,我得到的只是 C:/fakepath/image.png

有没有办法访问实际文件数据,以便我可以将其上传到我的 API?

<小时/>

代码

我的 FormControl 声明:

/**
 * Category of the product
 */
public category = new FormControl('', [
  Validators.required
]);

/**
 * Name of the product
 */
public name = new FormControl('', [
  Validators.required,
  Validators.minLength(3)
]);

/**
 * Description of the product
 */
public description = new FormControl('', [
  Validators.required
]);

/**
 * Price of the product
 */
public price = new FormControl('', [
  Validators.required
]);

/**
 * Image of the product
 */
public image = new FormControl('', [
  Validators.required
]);

我的页面/组件构造函数:

constructor(private api: ApiService,
  private formBuilder: FormBuilder) {

    this.productForm = formBuilder.group({
      category: this.category,
      name: this.name,
      description: this.description,
      price: this.price,
      image: this.image
    });
}

我当前如何尝试访问该文件

public async createProduct(): Promise<any> {
  console.log(this.image.value);
}

最佳答案

第 1 步:HTML 模板 (file-upload.component.html)

定义类型文件的简单输入标签。向 (change)-event 添加一个函数来处理选择文件。

<div class="form-group">
    <label for="file">Choose File</label>
    <input type="file"
           id="file"
           (change)="handleFileInput($event.target.files)">
</div>

第 2 步:在 TypeScript 中进行上传处理(在组件文件中)

为所选文件定义默认变量。

fileToUpload: File = null;

创建您在文件输入标记的(更改)事件中使用的函数:

handleFileInput(files: FileList) {
    this.fileToUpload = files.item(0);
}

第3步:文件上传服务

通过 POST 方法上传文件,您应该使用 FormData,因为这样您就可以将文件添加到 http 请求。

postFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    // Append image file to formdata as a seperate property
    formData.append('fileKey', fileToUpload, fileToUpload.name);

    // Append reactive form data too in a seperate property
    formData.append('productForm', JSON.stringify(this.productForm, null, 4));
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

关于javascript - 文件上传控件响应式(Reactive)表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54982798/

相关文章:

javascript - 错误 : property 'subscribe' does not exist on type 'OperatorFunction<{}, {} |可观察<任意>>

javascript - 如何订阅子路由中的参数变化?

javascript - 使用过滤器或管道将产品类别加载到 Ionic 2 的页面中?

javascript - d3 v4 : How to make a path being curved when only start and end point are known?

javascript - 如何在 Node.JS 中接收 req.body.model 的整个对象而不是单独接收它的所有变量?

javascript - 使用 jQuery 将具有特定类的每个 div 的名称保存到变量

javascript - 在 onClick 函数中添加字符串参数?

angular - Angular2 Router 中有抽象状态吗?

javascript - 将文件转换为字节值数字数组

angular - 找不到 npm flatmap-stream@0.1.1