【发布时间】:2021-09-11 05:14:03
【问题描述】:
我有问题。就是我无法上传图片。我尝试使用“邮递员”来上传图片,后端识别它并加载完美。但是对于 Angular,这不会发生在我身上,它总是将输入文件识别为“null”。如何在表单旁边上传图片?谢谢!
我收到了这个表格:
<form #createMenu="ngForm" (ngSubmit)="onSubmit(createMenu)" style="border: 1px solid; padding: 20px; display:flex; justify-content:center; flex-direction: column;" enctype="multipart/form-data">
<mat-form-field appearance="fill">
<mat-label>Title</mat-label>
<input matInput placeholder="example: Pizza" name="title" #title="ngModel" [(ngModel)]="menu.title" required>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Description</mat-label>
<textarea matInput name="description" placeholder="example: All of our pizzas are amazing" #description="ngModel" [(ngModel)]="menu.description" required></textarea>
</mat-form-field>
<br>
<label>Image of menu *</label>
<input type="file" name="image" placeholder="example: All of our pizzas are amazing" #image="ngModel" [(ngModel)]="menu.image" required/>
<br>
<input type="submit" class="submit" value="SEND"
[disabled]="!createMenu.form.valid" style="border:none; background:#181818; height: 40px; color: #f1f1f1; font-size: 22px;" />
</form>
这是我的服务:
create(menu:Menu):Observable<any>{
//Convierte a json el objeto
let json = JSON.stringify(menu);
//Guardamos las cabeceras con los datos del post
const headerDict = {
'Authorization': 'Bearer '+localStorage.getItem('token'),
'Content-Type': 'multipart/form-data',
'X-Requested-With': 'XMLHttpRequest',
}
const requestOptions = {
headers: new HttpHeaders(headerDict),
};
//Peticion ajax a la url
return this._http.post(this.url+'menu/create', json, requestOptions);
}
最后是我的组件:
public status: string;
public menu: Menu;
constructor(private _AdminmenuService:AdminmenuService) {
this.status = "";
this.menu = new Menu(1, '', '', '');
}
onSubmit(form:any){
this._AdminmenuService.create(this.menu).subscribe(
response => {
this.status = response.status;
if (response.status == "success") {
form.reset();
}
},
error => {
console.log(error);
}
);
}
【问题讨论】:
标签: angular