[英]Angular request POST with Multipart/FormData - Error
I have to upload with a Post a file, but I never have did it.我必须上传一个 Post 文件,但我从来没有这样做过。 I try this way, in debug I can see the FormBuilder getting the value of the upload, but I don't know if this way it's correct.我尝试这种方式,在调试中我可以看到 FormBuilder 获取上传的值,但我不知道这种方式是否正确。 I search in many documents, but I can't get it.我在很多文件中搜索,但我无法得到它。 I want to do this with a FormGroup, but just sending the file and the values for URL it's good for me.我想使用 FormGroup 执行此操作,但仅发送文件和 URL 的值对我来说很好。
edit-student.component.html编辑-student.component.html
<form [formGroup]="billsForm" (ngSubmit)="onSubmit()">
<br>
<mat-accordion>
<mat-expansion-panel hideToggle *ngFor="let month of months">
<mat-expansion-panel-header>
<mat-panel-title>
<select class="selectMonth" formControlName="month">
<option *ngFor="let month of months" [value]="month.value">
{{month.viewValue}}
</option>
</select>
</mat-panel-title>
<mat-panel-description>
Boleto do mês de {{month.viewValue}}
</mat-panel-description>
</mat-expansion-panel-header>
<input formControlName="upload" id="uploadB" class="uploadBoleto" type="file"
accept="application/pdf"><br>
<input class="uploadBoleto" type="submit" value="Enviar">
</mat-expansion-panel>
</mat-accordion>
</form>
edit-student.component.ts编辑-student.component.ts
ngOnInit(): void {
this.billsForm = this.fbills.group({
_id: [this.student.datakey._id],
course: [this.student.datakey.course],
sYear: [this.student.datakey.sYear],
month: [],
upload: [],
})
}
onSubmit() {
debugger
return this.editService.upload(this.billsForm.value).then((result:any)=>{
console.log('sucess')
}).catch((error:any)=>{
console.log(error)
});
}
edit-student.service.ts编辑-student.service.ts
upload(bill:BillsModel) {
debugger
let headerGet = new HttpHeaders();
let formData = new FormData();
let key = String(bill._id);
formData.append(key, bill.upload);
headerGet = headerGet.append('enctype', 'multipart/form-data');
headerGet = headerGet.append('key', this.user.token);
const requestOptions = {
headers: headerGet,
};
return new Promise ((resolve, reject)=>{
const url = this.config.API_URL + '/bills/create/' + bill.course + '/' + bill.sYear + '/' + bill.month + '/' + bill._id;
console.log(url);
this.http.post<any>( url, formData, requestOptions).subscribe((result:any)=>{
resolve(result);
}, (error)=>{
reject(error)
})
})
}
bills.model.ts bills.model.ts
export class BillsModel{
_id: number;
sYear: number;
month: number;
status: string;
course: string;
upload: any;
}
This is an example of how to upload a file with angular service:这是如何使用 angular 服务上传文件的示例:
public uploadFile(body: any, id: string): Observable<any>{
const formData = new FormData();
formData.append('file', body);
return this.httpClient.post<any>(config.serviceBaseUrl + '/file/save/'+id, formData,);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.