How to receive formdata value and upload image in react native and php?

  axios, php, react-native

I am trying to upload images in React Native and PHP. I am sending the values to PHP but I think I can not take them properly.

Here is my react-native side below

_pickDocument = async () => {
let result = await DocumentPicker.getDocumentAsync({});
// alert(result.uri);
console.log(result);

if (!result.cancelled) {
  this.setState({ image: result });
  console.log('source=====> ', this.state.image)

  const formData = new FormData();
  formData.append('file_attachment',result);

  axios.post('http://192.168.1.102/partner_project_backend/user_registration.php', {
    photo: formData,
  },
  )


    .then((response) => { 
      console.log(response)

      if (response.status == 1) {
        alert('Upload Successful');
      }
      else {
        // If no file selected the show alert
        alert('Sorry, there was an error uploading your file.');
      }

    })
    .catch((error) => {
      console.error(error);
    });

  }
}

And my PHP file

<?php
if(!empty($_FILES['file_attachment']['name']))
{
  $target_dir = "uploads/";
  if (!file_exists($target_dir))
  {
    mkdir($target_dir, 0777);
  }
  $target_file = $target_dir . basename($_FILES["file_attachment"]["name"]);
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
  // Check if file already exists
  i
  if (move_uploaded_file($_FILES["file_attachment"]["tmp_name"], $target_file))
  {
    echo json_encode(array( "status" => 1, "data" => array(), "msg" => "The file " .  basename( $_FILES["file_attachment"]["name"]) . " has been uploaded."));
  } 
  else
  {
    echo json_encode(array( "status" => 0, "data" => array(), "msg" => "Sorry, there was an error uploading your file."));
  }
}
?>

It is been a few days since I could find the solution. How can I solve it?
Or do you know any other usage or any website/video that I can try to use?

Source: Ask PHP

LEAVE A COMMENT