Search code examples
react-nativepostaxiosmultipart

Axios React upload jpg


I have photo file taken with ImagePicker, and I need upload it to server, using axios, and I need send type as a string with this photo.

My code here

const axiosMultipart = axios.create({
  timeout: 3000,
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})
uploadDocs(token,type,photo){
    let data = new FormData();
    data.append('photo', photo);
    data.append('type', type);

    return axiosMultipart
    .post(
      `uploadDocs`,
      {data},
      {
        headers: {
          Authorization: token,
        },
      }
    )
    .then((response) => {
      return response.data;
    })
    .catch((error) => console.log("uploadDocs: " + error));
  };

Server response is error_code 400 What is wrong here? Also I have code on php with a working request enter image description here


Solution

  • Try With Below Code,

        var photo = {
            uri: file,
            type: 'image/jpeg',
            name: 'photo.jpg',
        };
    
    
    var FormData = require('form-data');
    var form = new FormData();
    form.append('photo', photo);
    form.append('filetype', filetype);
    
    
    axios({
        method: 'post',
        headers: {
            "Accept": "application/json",
            'Content-Type': 'multipart/form-data',
            "Authorization": authData
    
        },
        data: form,
        url: `${base_url}`,
      
    }).then(async (result) => {
        console.log("uploadFile detail Response===>", result);
    
       
    }).catch((error) => {
        console.log("uploadFile detail error===>", error);
    
        callback({ status: false, result: error })
    });