I have a problem. And it is that I can not upload an image. I have tried using "Postman" with the image upload and the backend recognizes it and loads perfect. But with Angular, this doesn't happen to me, it always recognizes the input file as "null". How could I do an image upload next to my form? Thank you!
i got this form:
<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>
And this is my Service:
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);
}
And finally my Component:
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);
}
);
}