I have a form and I want to submit files too. I tried my API in postman and it works. But when I try to do it in angular I just couldn't find a way to make it work.
I tried many ways to do it but couldn't make it work
I created a User
model:
export class User {
public title: string;
public name: string;
public age: string;
public userFile: any;
}
In the user component user.component.ts
I declared a user model variable and a method on submit :
model = new User();//user model object
In the submit method I did set the content type to '' and submitted the data.
submit(){
console.log(this.model);
const headers = new HttpHeaders().set('Content-Type', '');
this.http.post('.../users/create', this.model, {headers}).subscribe(res => {
console.log("successs " + data);
},
err => {
console.log("error" + err)
});
}
And the HTML:
<form (submit)="submit()">
<div class="form-group">
<label for="title">UserId</label>
<input type="text" class="form-control" id="title" required [(ngModel)]="model.title" name="title">
</div>
<div class="form-group">
<label for="author">User Name</label>
<input type="text" class="form-control" id="author" required [(ngModel)]="model.name" name="author">
</div>
<div class="form-group">
<input type="file" id="userFile" #userFile="ngModel" [(ngModel)]="model.userFile">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
When I submit the form I get the error:
422 Unprocessable Entity
In the inspect element I see that body request was:
{
"title": "lorem",
"name": "Test",
"age": "35",
"userFile": "C:\\fakepath\\testimage.png"
}
Can someone help me, please?