lundi 6 janvier 2020

Correct way to post file to Laravel server using Angular 8

I am trying to post an array of files along with some other data to a laravel server using angular. The file information gets set on the angular side and File object is there when the data is posted. However if I just return the request, the File data has been removed and I get a empty array. The rest of my data is fine though.

My service code:

storeChecklistAnswers(checklistAnswers: ChecklistAnswersModel) {
        return this.http
            .post<any>(
                `${environment.apiUrl}/checklist/answers/store`,
                checklistAnswers,
                {
                    reportProgress: true,
                    headers: new HttpHeaders().append(
                        'enctype',
                        'multipart/form-data'
                    )
                }
            )
            .pipe(
                catchError(error => {
                    console.log(error);
                    let errors;
                    if (error.error.errors) {
                        errors = {
                            message: error.message,
                            errors: Object.values(error.error.errors)
                        };
                    } else if (error.error.message) {
                        errors = {
                            message: error.error.message
                        };
                    } else {
                        errors = {
                            message:
                                'An unknown error has occured. Please refresh the application'
                        };
                    }
                    return throwError(errors);
                }),
                tap(resultData => {
                    return resultData;
                })
            );
    }

In my controller

return response()->json([
            'data' => $request->all()
        ]);

The data before it is posted:

images: Array(1)
0:
file: File
name: "292588.jpg"
lastModified: 1568349822014
lastModifiedDate: Fri Sep 13 2019 06:43:42 GMT+0200 (South Africa Standard Time) {}
webkitRelativePath: ""
size: 282431
type: "image/jpeg"
__proto__: File

The actual response

images: Array(1)
0:
file: []

I have tried to remove the headers as suggested in some SO answers, but I get the same result I have also checked file_uploads, upload_max_filesize, post_max_size in php.ini.

I am running out of ideas. Please could someone point me in the right direction. I am not sure why I cant post the file?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire