reactjsreact-nativeaxiosfetchmultipartform-data

react native post form data with object and file in it using axios


enter image description here

so i want to upload object as data and file as Note to api using axios

uploadToServer= () => {
    const file =this.state.photo

  let data2 ={sale_id:1,
            note_type_id:4,
            description:"test",
            note_content_item:" hi from broker hub"
            
            }



let data = new FormData()
data.append('data[sale_id]', '1')
data.append('data[note_type_id]', '4')

data.append('data[description]', "test")

data.append('data[note_content_item]', "test")







console.log(data)


axios({
  url: api',
  method: 'POST',
  data: data,
  headers: {
   
            'Content-Type' : 'multipart/form-data',
          'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='

  }
})
        .then(resp => console.log(resp.data.response))
        .catch(error => console.error(error)); 

}

first i am trying with data without Note i can do it in postman

enter image description here

but with my code i got error

message: "Can not save file" response_code: 10

i got this error only if i change the key from data to something else enter image description here


Solution

  • You are not building FormData correctly, Try this:

    let data = {sale_id:1,
                    note_type_id:4,
                    description:"test",
                    note_content_item:" hi from broker hub"            
                    }
    const formData = new FormData();
    formData.append('data', JSON.stringify(data));
    formData.append('Note', {
                         uri: "file://" //Your Image File Path
                        type: 'image/jpeg', 
                        name: "imagename.jpg",
                      });
    axios({
           url    : api,
           method : 'POST',
           data   : formData,
           headers: {
                        Accept: 'application/json',
                        'Content-Type': 'multipart/form-data',
                        'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
                    }
                })
                .then(function (response) {
                        console.log("response :", response);
               })
               .catch(function (error) {
                        console.log("error from image :");
               })