axios post FormData (react native -> laravel) adding multiple levels

1.8k views Asked by At

I'm creating a react native app where i have a form with text and picture.

I use axios to post the form as follow:

// create a formData to have my text and picture in two objects
let formData = new FormData();

let dataSheet = {
    'user_id' : user_id,
    'title' : title,
    'information' : information,
    'rubrique' : rubrique,
    'date' : date, 
}

formData.append('sheet', JSON.stringify(dataSheet)); 

// if we have a picture, we add it
if (picture !== '') {
    let localUri = picture.uri;
    let filename = localUri.split('/').pop();
    let match = /\.(\w+)$/.exec(filename);
    let type = match ? `image/${match[1]}` : `image`;
    formData.append('picture', { uri: localUri, name: filename, type });
}

// The endPoint is my laravel api with a protected route
axios.post(endPoint, {
   formData
}, {
    withCredentials: true
}).then((response) => { 
    dispatch({type: 'SAVING_SHEET_FULFILLED', payload: response.data})    
}).catch((error) => {
    console.log(error.response)
})

But I got this from the request inside my laravel controller when I do var_dump($request->all())

FormData {
  "_parts": Array [
    Array [
      "sheet",
      "{\"user_id\":1,\"title\":\"Titre\",\"information\":\"Infor\",\"rubrique\":\"\",\"date\":\"\"}",
    ],
    Array [
      "picture",
      Object {
        "name": "2FE9F6EB-9A72-45AE-A72C-B6F4303B63F9.jpg",
        "type": "image/jpg",
        "uri": "file:///Users/romualdjarno/Library/Developer/CoreSimulator/Devices/0E44F890-6BB9-42C0-9C0A-7F46243A1457/data/Containers/Data/Application/5298E43E-5D24-4B13-9D8E-50AF18262CC2/Library/Caches/ExponentExperienceData/%2540anonymous%252Fwikime-ec912bd0-c27c-4b39-ab70-26e8279f7626/ImagePicker/2FE9F6EB-9A72-45AE-A72C-B6F4303B63F9.jpg",
      },
    ],
  ],
}

Instead, I need to have 'sheet' and 'picture' arrays only.

1

There are 1 answers

1
Mateusz Pęczkowski On

First of all, you need to add enctype="multipart/form-data" at form.

Second don't use $request->all(). To get files use: $request->file('name')

Source (from the documentation): LINK