使用multipart / form-data在Angular 6中发送文件

时间:2019-01-30 17:09:37

标签: angular multipartform-data angular-reactive-forms angular-httpclient

我尝试将两个字段发送到后端服务。一个是公用字符串,另一个是文件字段。当我尝试使用Http客户端的post方法时,服务器收到500错误消息,告诉我内容类型不是多部分请求。

add-new-language.component.html

<form [formGroup]="form" (ngSubmit)="sendForm()">
  <input
     type="file"
     formControlName="file"
     (change)="onFileChanged($event)"
  />
  <mat-form-field class="new-language__language-select">
    <mat-select placeholder="Seleziona la lingua" formControlName="language">
      <mat-option *ngFor="let lang of languages" [value]="lang.id">{{lang.label}}</mat-option>
    </mat-select>
  </mat-form-field>
  <button mat-raised-button [disabled]="form.invalid">Upload</button> 
</form>

add-new-language.component.ts

export class AddNewLanguageComponent implements OnInit {
  @Input() languages: Type[];
  form: FormGroup;
  file: File;
  constructor() {
    private fb: FormBuilder;
    private dictionariesService: DictionariesService;
  }

  ngOnInit() {
    this.initForm();
  }

  private initForm(): void {
    this.form = this.fb.group({
      file: [null, Validators.required],
      language: [null, Validators.required]
    });
  }

  onFileChanged(event): void {
    if (event.target.files && event.target.files.length) {
      this.file = <File>event.target.files[0];
    }
  }

  sendForm(): void {
    this.dictionariesService
    .saveSynonymsFile(this.form, this.file)
    .subscribe(response => console.log(response));
  }
}

dictionaries.service.ts

saveSynonymsFile(form: FormGroup, file: File): Observable<DictionaryFile> {
  const formData = new FormData();
  formData.append('lang', form.value.language);
  formData.append('synonyms', file);
  return this.http.post<DictionaryFile>(
    `${this.querySettingsUrl}/synonyms`,
    formData
  );
}

我也尝试用Content-Type强制HttpHeaders:multipart / form-data,但无所事事。浏览器始终通过Content-Type发送数据:application / json

1 个答案:

答案 0 :(得分:0)

不是创建用于保存文件的服务,而是从@rxweb导入RxFormBuilder,创建其对象并使用toFormData()方法将json数据转换为formData,在这里我通过了api的链接服务器端供您参考,它将把fileObject传递给服务器。在HTML中添加[writeFile]="true"时,无需调用onFileChanged($ event)

Component.html:

export class AddNewLanguageComponent implements OnInit {
  @Input() languages: Type[];
  form: RxFormGroup;
  api:string = 'api/User'
  constructor(private fb: RxFormBuilder,private http: HttpClient) {}

  ngOnInit() {
    this.initForm();
  }

  private initForm(): void {
    this.form = <RxFormGroup>this.fb.group({
      file: [null, Validators.required],
      language: [null, Validators.required]
    });
  }



  sendForm(): void {
      let formdata = this.form.toFormData()
        this.http.post(this.api, formdata); // This is fake uri, This is just for your reference
  }
} 

在component.html中:

<form [formGroup]="form" (ngSubmit)="sendForm()">
  <input
     type="file"
     formControlName="file"
     [writeFile]="true"
  />
  <mat-form-field class="new-language__language-select">
    <mat-select placeholder="Seleziona la lingua" formControlName="language">
      <mat-option *ngFor="let lang of languages" [value]="lang.id">{{lang.label}}</mat-option>
    </mat-select>

  <button>Upload</button> 
</form>

Stackblitz