Home > Mobile >  unable to send form-data in react-native
unable to send form-data in react-native

Time:04-02

I was using axios to send form-data in RN but it's not working. Noww tried fetch every feild uploads except images. If i use postman, everything works fine.enter image description here

here is my code:

const postOrder = () => {
    var data = new FormData();
    data.append('marca', marca);
    data.append('modeo', modeo);
    data.append('option', option);
    data.append('descripcion', descripcion);
    data.append('images[]', images);
    data.append('userId', '2');
    dispatch(saveOrder(data));
  };
    fetch(`${baseUrl}/save-order`, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
    body: data,
  })
    .then(res => res.json())
    .then(json => {
      // dispatch({type: 'ORDER', payload: response.data});
      console.log('json1', json);
    })
    .catch(error => {
      console.log(error);
    });

every property/feild is beig uploaded except images. I have tried these methods also

data.append('file', {
      uri: images,
      type: 'image/jpeg',
      name: 'images[]',
    });
data.append('file',images,'images[])

CodePudding user response:

const formData = new FormData();
    formData.append('file', {
      uri: pictureUri,
      type: 'image/jpeg',
      name: 'profile-picture'
})

I had the same issue, Adding type: 'image/jpeg', to the file attribute of the formData fixed it.

CodePudding user response:

Axios didn't worked for me but fetch api did. here's my working code: Post function

const postOrder = () => {
    var data = new FormData();
    data.append('marca', marca);
    data.append('modeo', modeo);
    data.append('option', option);
    data.append('description', description);
    data.append('images[]', {
      uri: images,
      name: 'image.jpg',
      type: 'image/jpeg',
    });
    data.append('userId', state.user.id);
    dispatch(saveOrder(data));
  };

Fetch api

 fetch(`${baseUrl}/save-order`, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
    body: data,
  })
    .then(res => res.json())
    .then(json => {
      console.log('json1', json);
    })
    .catch(error => {
      console.log(error);
    });
  • Related