Rilesh Patel
Rilesh Patel

Reputation: 13

Image upload using react-native and php does not work

I am uploading an image using react-native and my API is PHP based. When I test my API using Post Man it works correctly but when I pass an image from the react-native app it shows me an error-

SyntaxError: JSON Parse error: Unexpected end of input

Here is the code for sending an image using the POST method at the react-native side-

uploadImageToServer = () => {

    const data = new FormData();
        data.append('image', {
          name: this.state.name, // rn_image_picker_lib_temp_b9855c66-9093-433e-af06-475ef6e82a3f.jpg
          type: this.state.type, // image/jpeg
          uri: this.state.uri, // file:///data/user/0/com.tmbs_ekta/cache/rn_image_picker_lib_temp_b9855c66-9093-433e-af06-475ef6e82a3f.jpg
     });

    fetch('https://tmbsbavan.com/api/family_method.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      body: data,
    }).then((response) => response.json())
    .then((json) => {
      console.log(json);

    }).catch((err) => { console.log(err); });
 
  }

Server-side PHP code-

<?php
    $target_dir = "profile_pic";
    $target_dir = '../'.$target_dir . "/" .rand() . "_" . time() . ".jpeg";
    
    if(move_uploaded_file($_FILES['image']['tmp_name'], $target_dir)){
        $MESSAGE = "Image Uploaded Successfully." ;
        echo json_encode($MESSAGE);
    }
?>

Please help me with how can I solve this issue. In Postman the API is working properly but in react native. it's showing an error.

Upvotes: 1

Views: 597

Answers (1)

JSONCMD
JSONCMD

Reputation: 75

An unconfigured cors may be the problem

<?php
header("Access-Control-Allow-Origin: *");

Upvotes: 1

Related Questions