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

问题描述 投票:0回答:1

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

附加新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>

附加新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发送数据

angular multipartform-data angular-reactive-forms angular-httpclient
1个回答
0
投票

而不是创建用于保存文件的服务,从@rxweb导入RxFormBuilder,创建其对象并使用将json数据转换为formData的toFormData()方法,这里我已经在服务器端传递了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

© www.soinside.com 2019 - 2024. All rights reserved.