Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 935
Firas Abu Fares Avatar asked May 21 '19 09:05

Firas Abu Fares


2 Answers

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 :");
           })
like image 98
Rocky Avatar answered Nov 13 '22 05:11

Rocky


when you are using react-native you don't need "form-data" package. Because react native polyfills standard FormData api and exports it as global.

second problem is axios converts form data automatically to string, so you need to use transformRequest config on request to override it.

import { AxiosRequestConfig } from "axios";
const FormData = global.FormData;

const axiosInstance = axios.create({
    baseURL: 'example.com', // use with scheme
    timeout: 30000,
    headers: {
        "X-Platform": 'iOS',
        "X-App-Build-Number": '1.0.0',
    },
});

const formData = new FormData();
formData.append("userId", "123456");
formData.append("file", {
    uri: "/dev/sda/abc.png",
    type: "image/png",
    name: "abc.png",
});

const config: AxiosRequestConfig = {
    method: "post",
    url: "/process/start",
    responseType: "json",
    headers: {
        'Content-Type': 'multipart/form-data',
        // if backend supports u can use gzip request encoding
        // "Content-Encoding": "gzip",
    },
    transformRequest: (data, headers) => {
        // !!! override data to return formData
        // since axios converts that to string
        return formData;
    },
    onUploadProgress: (progressEvent) => {
        // use upload data, since it's an upload progress
        // iOS: {"isTrusted": false, "lengthComputable": true, "loaded": 123, "total": 98902}
    },
    data: formData,
};

// send post request and get response
const response = await axiosInstance.request(config);
like image 33
user_2738046 Avatar answered Nov 13 '22 07:11

user_2738046