Search code examples
laravel-5vuejs2axiosform-data

axios/laravel/formdata post request is empty


I want to upload some files, but when i post with axios, my formdata is an empty request in laravel

vuejs: uploader.vue

filesChange(e) {
    const fileList = e.target.files;
    const formData = new FormData();
    if (!fileList.length) return;
    for (let i = 0; i < fileList.length; i += 1) {
      console.log(fileList[i]);
      formData.append('files', fileList[i], fileList[i].name);
    }
    this.save(formData);
  },

output from console, all files are looped and appended to formData output from console, all files are looped and appended to formData

save(formData) {
    photosApi.storePhotos(formData, this.galleryId).then((response) =>     {
        console.log(response);
    }).catch((error) => {
        console.log(error);
    });
},

vuejs: photosApi.js

storePhotos(formData, id) {
    return axios.post(`api/photo/${id}`, formData);
},

when i inspect my api-call i see this when i inspect my api-call i see this

laravel: api.php

Route::post('/photo/{id}',  'PhotoController@store');

laravel: PhotoController.php

public function store(Request $request, $id)
{
    return $request->all(); 
}

the return of my response is only empty... the return of my response is only empty...

what im'doing wrong?


Solution

  • I solved it finally :)

    the first problem was this line

    formData.append('files', fileList[i], fileList[i].name);
    

    append was always overwriting the last "files" entry... (i thought it was working like push)

    so the first fix was

    formData.append(`file${i}`, fileList[i], fileList[i].name);
    

    to see the data don't use

    return $request->all();
    

    instead use

    print_r($request->all());
    

    now you can see something usefull when you inspect your apicall

    enter image description here

    now it was easy

    $data = $request->all();
    foreach ($data as $key => $file) {
        $file->move('/public/images', $file->getClientOriginalName());
    };
    

    all my files are stored in my folder ;)

    UPDATE: I found out, if i write files with "[]" then i get also the data as an array

    for (let i = 0; i < fileList.length; i += 1) {
        formData.append('files[]', fileList[i], fileList[i].name);
    }
    

    And in my controller i get access to my files with this line, but without the "[]"

    $files = $request->file('files');