具有多部分形式的 Angular 6 后请求不包含已发布对象的附加文件

标签 angular file typescript post file-upload

我正在尝试通过 Angular 6 将表单连同文件一起发送到我的 API,但帖子不包含该文件,即使应该发送的对象包含在内。

当我查看控制台日志时,我看到了预期的内容,amount:"amount", invoicefile: File.... 但在传出请求中,该字段显示 invoicefile:{},现在文件已在另一端收到。最后附上一些图片。

最后,我的 API 告诉我所有字段都丢失了,但我认为这是另一个问题。

组件看起来像这样:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { first } from 'rxjs/operators';
import { FormGroup, FormBuilder, FormControl, Validators, FormArray, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

import { AlertService } from '../_services';
import { InvoiceService } from '../_services';
import { Invoice } from '../_models';

@Component({
  selector: 'app-registerinvoice',
  templateUrl: './registerinvoice.component.html',
  styleUrls: ['./registerinvoice.component.css']
})
export class RegisterinvoiceComponent implements OnInit {
  public registerForm: FormGroup;
  public submitted: boolean;

  constructor(
    private router: Router,
    private invoiceService: InvoiceService,
    private alertService: AlertService,
    private http: HttpClient,

  ) { }
  fileToUpload: File = null;

  ngOnInit() {
    this.registerForm = new FormGroup({
      serial: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]),
      amount: new FormControl('', [<any>Validators.required, <any>Validators.minLength(4)]),
      debtor: new FormControl('', [<any>Validators.required, <any>Validators.minLength(10)]),
      dateout: new FormControl('', [<any>Validators.required, <any>Validators.minLength(8)]),
      expiration: new FormControl('', [<any>Validators.required, <any>Validators.minLength(8)]),
    });
  }
  handleFileInput(files: FileList){
    this.fileToUpload=files.item(0);
  }

  deliverForm(invoice: Invoice, isValid) {
    this.submitted=true;
    if (!isValid){
      return;
    }
    invoice.invoicefile=this.fileToUpload;
    console.log(invoice);
    console.log(typeof(invoice.invoicefile));
    this.invoiceService.create(invoice)
      .pipe(first())
      .subscribe(
        data => {
          this.alertService.success('Invoice successfully uploaded', true);
          this.router.navigate(['/profile']);
        },
        error => {
          this.alertService.error(error);
        });
  }

}

后面是提供帖子的服务:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Http } from '@angular/http';
import { Invoice } from '../_models';
import { FormGroup } from '@angular/forms';

const HttpUploadOptions = {
  headers: new HttpHeaders({ "Content-Type": "multipart/form-data" })
}
@Injectable({
  providedIn: 'root'
})
export class InvoiceService {

  constructor(
    private http: HttpClient
  ) { }
  create(invoice: Invoice){
    return this.http.post('/api/v1/invoices/', invoice, HttpUploadOptions)
  }
}

最后是类:

export class Invoice {
    id: any;
    serial: any;
    amount: any;
    debtor: any;
    dateout: any;
    expiration: any;
    fid: any;
    invoicefile: File;
}

看起来正确的控制台日志:enter image description here

以及文件丢失的传出请求: enter image description here

编辑:

现在创建的服务代码如下所示:

create(invoice: Invoice){
    let payload=new FormData();
    payload.append('amount', invoice.amount);
    payload.append('debtor', invoice.debtor);
    payload.append('serial', invoice.serial);
    payload.append('dateout', invoice.dateout);
    payload.append('expiration', invoice.expiration);
    payload.append('invoicefile', invoice.invoicefile);
    return this.http.post('/api/v1/invoices/', payload, HttpUploadOptions)
  }

响应看起来像这样。对我来说看起来很奇怪,我的后端仍然有一些错误,但这是另一个问题。 enter image description here

最佳答案

您的 POST 请求正文实际上是 JSON,而不是您希望的多部分(尽管 Content-Type header 说的是什么)。

为了解决这个问题,您需要构建一个 FormData 对象,然后在您的请求中使用它:

let input = new FormData();
// Add your values in here
input.append('id', invoice.id);
input.append('invoiceFile', invoice.invoiceFile);
// etc, etc

this.http.post('/api/v1/invoices/', input, HttpUploadOptions)

关于具有多部分形式的 Angular 6 后请求不包含已发布对象的附加文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50572363/

相关文章:

angular - 从深度嵌套的目录结构中导入模块

typescript - typescript 中带有n个参数的通用 curry 函数

typescript - 如何获得具有递归泛型类型的后代名称的联合?

angular - 附加到门户时仅初始化一次组件

ubuntu - Angular2 Quickstart gulp错误

java - 通过 Spring by Environment 注入(inject)属性值

windows - 在 Windows 上,如何检测文件的行尾?

ruby-on-rails - Angular 4 和 Rails 5 发布请求 JSON 格式化

javascript - 错误 : Type String is not assignable to type '{ name : string; }' in Angular

我可以从具有许多编译器标志的 c 程序中导出使用过的代码吗?