Skip to content
Advertisement

How to upload files from react native app to PHP server?

I developed a PHP project, now I am working on connecting it to react native app. However, I tried many codes to upload image to the server nothing works.

Here is my code example,

  const uploadImage = async () => {
// Check if any file is selected or not
if (singleFile != null) {
  // If file selected then create FormData
  const fileToUpload = singleFile;
  const data = new FormData();
  data.append('file_attachment', fileToUpload);
  // Please change file upload URL
  fetch(
    'http://192.168.8.105/insaf/mobileConnection/upload.php',
    {
      method: 'post',
      body: data,
      headers: {
        'Content-Type': 'multipart/form-data; ',
      },
    }
  ).then((response) => response.json())
    .then((responseJson) => {
      //Hide Loader
      setLoading(false);
      console.log(responseJson);
      // If server response message same as Data Matched
      if (responseJson[0].Message == "Success") {

        navigation.replace('ReqPriceList');
      } else {
        //setErrortext(responseJson.msg);
        console.log('Please check');

      }
    })
    .catch((error) => {
      //Hide Loader
      setLoading(false);
      console.error(error);
    });

} else {
  // If no file selected the show alert
  alert('Please Select File first');
}

};

And for the PHP server side (upload.php), here is the code

if(!empty($_FILES['file_attachment']['name']))
{
  $target_dir = "../assets/files/request/";
  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
  if (file_exists($target_file)) {
    echo json_encode(
       array(
         "status" => 0,
         "data" => array()
         ,"msg" => "Sorry, file already exists."
       )
    );
    die();
  }
  // Check file size
  if ($_FILES["file_attachment"]["size"] > 50000000) {
    echo json_encode(
       array(
         "status" => 0,
         "data" => array(),
         "msg" => "Sorry, your file is too large."
       )
     );
    die();
  }
  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."
      )
    );
  }
}

I got this code from here https://aboutreact.com/file-uploading-in-react-native/

And I am getting

this error

Can anyone help me? Any alternative solution will be fine.

Edit:

based on @Sadia Chaudhary code this function works

  let uploadImage = async () => {
//Check if any file is selected or not
if (singleFile != null) {
  //If file selected then create FormData

  const fileToUpload = singleFile;
  console.log("fileToUpload is " + fileToUpload);

  const uriPart = fileToUpload[0].uri;

  const fileExtension = fileToUpload[0].name.split('.')[1];
  console.log("fileExtension is " + fileExtension);

  const data = new FormData();

  //const uriPart = fileToUpload.split('.');
  //const fileExtension = uriPart[uriPart.length - 1];

  data.append('file_attachment', {
    uri: uriPart,
    name: `photo.${fileExtension}`,
    type: `image/${fileExtension}`
  });


  let res = await fetch(
    'http://myIp/insaf/mobileConnection/uploads.php',
    {
      method: 'post',
      body: data,
      headers: {
        'Content-Type': 'multipart/form-data; ',
      },
    }
  );
  let responseJson = await res.json();
  if (responseJson.status == 1) {
    
    alert('Upload Successful');
  }
} else {
  //if no file selected the show alert
  alert('Please Select File first');
}

};

Advertisement

Answer

The error has nothing to do with the image upload. You are facing this error because of response.json(). Also, try to convert image like this.

//retrive the file extension of your photo uri
const uriPart = imageSource.split('.');
const fileExtension = uriPart[uriPart.length - 1];

formData.append('photo', {
    uri: imageSource,
    name: `photo.${fileExtension}`,
    type: `image/${fileExtension}`
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement