You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 10中如何实现Blob文件的multipart/form-data上传

Angular 10 multipart/form-data 文件上传类型错误修复

问题根因

你碰到的Argument of type 'FormData' is not assignable to parameter of type 'Blob'错误来自两个代码问题:

  • 响应式表单默认不会自动读取<input type="file">选中的文件对象,你之前绑定的onSelection是不存在的事件,表单控件里存的根本不是有效的文件对象
  • 服务层uploadFile方法明确要求入参为Blob类型,你错误地构造了FormData对象尝试传入,类型完全不匹配

注:浏览器原生File类型本身就是Blob的子类,完全满足接口的Blob类型要求,不需要额外做类型转换。

修复步骤

  1. 修正模板代码
    把文件输入框不存在的onSelection事件替换为原生change事件,补全未闭合的按钮标签,修正后模板代码如下:
<form [formGroup]="customerFileGroup" (submit)="submit($event)">
  <div>
    <input
      formControlName="file"
      type="file"
      accept=".csv,text/plain,text/csv,text/html"
      (change)="changeFile($event)"
    />
  </div>
  <button type="submit">Submit</button>
</form>
  1. 修正组件逻辑
    统一表单变量名,新增文件选择处理方法把选中的真实File对象存入表单控件,提交时直接取出文件对象传入服务方法即可,不需要在组件层构造FormData(FormData封装逻辑应该在黑盒的服务方法内部处理),修正后组件代码如下:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-customer-file',
  templateUrl: './customer-file.component.html'
})
export class CustomerFileComponent {
  customerFileGroup: FormGroup;

  constructor(private readonly _fb: FormBuilder) {
    this.customerFileGroup = this._fb.group({
      file: [null]
    });
  }

  changeFile(e: Event): void {
    const fileInput = e.target as HTMLInputElement;
    if (fileInput.files?.length) {
      // 把选中的文件对象更新到表单控件
      this.customerFileGroup.patchValue({
        file: fileInput.files[0]
      });
    }
  }

  submit(e: Event): void {
    e.preventDefault();
    const selectedFile = this.customerFileGroup.get('file')?.value as File;
    if (!selectedFile) {
      // 补充未选择文件的提示逻辑即可
      return;
    }
    // 直接传入File对象,完全符合Blob类型要求
    this.customerFileService.uploadFile(selectedFile)
      .subscribe(response => {
        // 处理上传成功后的业务逻辑
      });
  }
}

注意事项

  • 你之前的代码存在变量名不一致问题:定义的表单名是customerFileGroup,提交逻辑里写的是fileUploadGroup,运行时会报属性不存在错误,必须统一变量名
  • 不要在组件层提前构造FormData:服务层方法签名只接收Blob,说明multipart/form-data的格式封装是在服务内部完成的,外层传FormData必然触发类型错误
  • 如果后续需要传额外参数,不要在组件层拼FormData,应该修改服务层方法入参,在服务内部统一构造FormData

内容的提问来源于stack exchange,提问作者Learn AspNet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 21:45:39