mardi 26 mars 2019

How to fix uploaded file data missing while posting from angular to Rest api in Laravel

I am trying to post data(upload file) from angular7 (ngx-admin) to a remote Laravel 5 REST API. This works when posting the data using Postman, but via the app, the uploaded file data was missing when I checked from Laravel api controller.

I tried to add Authorization header without Content-type header but it didn't solve the problem.

in Angular Component,

const fd = new FormData();
fd.append('name', 'Test');
fd.append('file', files[0], files[0]['name']);
this.api.addSlider('addImage', temp).subscribe( 
      res => {
        console.log('ok ', res);
      },
      err => {
        console.log('error ', err);
      },
    );

in Angular Api service,

addSlider(url, data): Observable<any> { 
        const httpOptionsAuthHeader = {
            headers: new HttpHeaders({
                'Authorization': 'Bearer ' + this.authSrv.getToken(),                
            }),
        };
        return this.http.post(apiUrl + url, data, httpOptionsAuthHeader)
            .pipe(
                catchError(this.handleError),
            );
    }

in Laravel Controller,

if($request->hasFile('file')) {
            $filenameWithExt = $request->all()['file']->getClientOriginalName();
            $fileName = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            $extension = $request->all()['file']->getClientOriginalExtension();
            $fileNameToStore = $request->all()['componentId'].'_'.$fileName.'.'.$extension;
            $path = $request->all()['file']->storeAs('public/slider_images', $fileNameToStore);
        }

And when I printed out for $request->all(), the result is { name: 'Test', file: [] }

Please advise me how to get the uploaded File object.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2UcijpV
via IFTTT

Aucun commentaire:

Enregistrer un commentaire