axios发布FormData(反应原生 - > laravel)添加多个级别

时间:2018-02-12 08:53:07

标签: laravel api react-native axios form-data

我正在创建一个反应本机应用程序,其中我有一个带有文本和图片的表单。

我使用axios发布表格如下:

// 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)
})

但是当我做var_dump($request->all())

时,我从我的laravel控制器内的请求中得到了这个
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",
      },
    ],
  ],
}

相反,我只需要'sheet'和'picture'数组。

1 个答案:

答案 0 :(得分:0)

首先,您需要在表单中添加enctype="multipart/form-data"

其次不要使用$request->all()。要使用文件:$request->file('name')

来源(来自文档):LINK