Reputation: 46
I'm sending an image file from Angular 13.0.4 to my Laravel 8 controller, but this file is not recognized by Laravel. It's like not sending anything.
When I try Postman or Insomnia it works perfectly fine.
My Laravel Controller is like this:
public function uploadimage(Request $request)
{
if ($request->hasFile('image'))
{
return response()->json(["message" => "A file was sent!"]);
}
else
{
return response()->json(["message" => "No file sent!"]);
}
}
Postman returns A file was sent!, white Angular returns No file sent!
My Courses.component.ts is like this:
export class CoursesComponent {
constructor(private http:HttpClient) { }
filedata:any;
/* File onchange event */
fileEvent(e:any){
this.filedata = e.target.files[0];
}
/* Upload button functioanlity */
onSubmitform(f: NgForm) {
var myFormData = new FormData();
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
myFormData.append('image', this.filedata);
/* Image Post Request */
this.http.post('http://fener.tachyonstudio.com/api/sample-restful-apis', myFormData, {
headers: headers
}).subscribe(data => {
console.log(data);
});
}
And my Courses.component.html is like this:
<form #f="ngForm" (ngSubmit)="onSubmitform(f)" enctype='multipart/form-data'>
<input type="file" name="image" (change)="fileEvent($event)"/>
<button>Upload Image</button>
</form>
I am new to Angular, so I have been stuck here for quite some time.
Upvotes: 1
Views: 680
Reputation: 398
Try to use enctype
instead of Content-Type
So Replace your :
headers.append('Content-Type', 'multipart/form-data');
by
headers.append('enctype', 'multipart/form-data');
Upvotes: 1