I am currently working on an Angular 7 project where I am trying to upload an image file along with other form data to a backend using Apache PHP. When I use the HttpClient to send a POST request with just the image alone, everything works smoothly.
// This is successful
uploadAvatar(payload: any): Observable<any> {
const formData = new FormData();
formData.set('avatar', payload.avatar);
return this.http.post(`${api_url}/user/avatar`, formData)
}
// However, this is not
create(payload: any): Observable<any>{
const formData = new FormData();
formData.set('title', payload.title);
formData.set('image', payload.image);
return this.http.post(`${api_url}/path/to/add`, formData);
}
Unfortunately, the POST request fails due to an OPTIONS preflight issue, where the server indicates that the image file is missing from the request data.
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I have attempted manually setting headers to
Content-Type: multipart/form-data
and Content-Type: application/x-www-form-urlencoded
, but without success.
I also tried using UrlSearchParams
and HttpParams
instead of FormData
, but encountered similar issues.
Interestingly, when testing the request in Postman, it functions correctly.