Angular 6包含多个部分的表单后请求不包含发布的对象的附件文件 [英] Angular 6 post-request with a multipart form doesn't include the attached file of the object posted
问题描述
我正在尝试通过Angular 6向我的API发送一个表单和一个文件,但是该帖子不包含该文件,即使应该发送的对象也包含了该文件.
I'm trying to send a form along with a file to my API through Angular 6, but the post doesn't include the file, even though the object that's supposed to be sent does.
当我查看控制台日志时,我看到了预期的值:金额:金额",发票文件:文件.... 但是,在外发请求中,该字段显示invoicefile:{},现在在另一侧接收到文件.最后包括一些图片.
When I'm looking at the console logs I see what is expected, amount:"amount", invoicefile: File.... But In the outgoing request the field shows invoicefile:{}, and now file is received on the other side. Some pictures are included at the end.
最近我的API告诉我所有字段都丢失了,但是我认为这是另一个问题.
Lastly my API is telling my all fields are missing, but I think that another problem.
该组件如下所示:
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);
});
}
}
接着是提供帖子的服务:
Followed by the service that provides the post:
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;
}
看起来正确的控制台日志:
The console log that looks correct:
以及缺少文件的传出请求:
And the outgoing request where the file is missing:
现在,用于创建的服务代码如下:
Now the service code for create looks like this:
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)
}
响应看起来像这样.对我来说看起来很奇怪,但后端仍然出现一些错误,但这是另一个问题.
And the response looks like this. Looks weird to me, and I'm still getting some errors from my back-end, but that's another question.
推荐答案
您的POST请求正文实际上是JSON,而不是您希望的Multipart(尽管Content-Type标头说了什么).
Your POST request body is actually JSON, not Multipart as you would hope (despite what the Content-Type header says).
为了解决这个问题,您需要构建一个FormData对象,并在请求中使用它:
In order to remedy that, you need to build a FormData object, and use that in your request instead:
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包含多个部分的表单后请求不包含发布的对象的附件文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!