PHP получает нулевые данные от React Native при загрузке изображений? - PullRequest
0 голосов
/ 30 июня 2018

Мне потребовалось некоторое время, чтобы понять, потому что на экране приложения все, что я получал, было JSON Parse Error: '<'. Благодаря error_log я нашел в PHP следующие ошибки:

[29-Jun-2018 19:35:34 America/Chicago] PHP Deprecated:  Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0
[29-Jun-2018 19:35:34 America/Chicago] PHP Warning:  explode() expects parameter 2 to be string, array given in React/user-image-upload.php on line 17
[29-Jun-2018 19:35:34 America/Chicago] PHP Warning:  end() expects parameter 1 to be array, null given in React/user-image-upload.php on line 18
[29-Jun-2018 19:35:34 America/Chicago] PHP Warning:  preg_match() expects parameter 2 to be string, array given in React/user-image-upload.php on line 27
[29-Jun-2018 19:35:34 America/Chicago] PHP Warning:  unlink() expects parameter 1 to be a valid path, array given in React/user-image-upload.php on line 30

А вот мой php-код для загрузки изображений:

    <?php
         // Getting the received JSON into $json variable.
 $json = file_get_contents('php://input');

 // decoding the received JSON and store into $obj variable.
 $obj = json_decode($json,true);

$fileName = $obj["userimgSource"]; // The file name
$fileTmpLoc = $obj["userimgSource"]; // File in the PHP tmp folder
$fileType = $obj["userimgSourceType"]; // The type of file it is
$fileSize = $obj["userimgSourceSize"]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
// START PHP Image Upload Error Handling --------------------------------------------------
if (!$fileTmpLoc) { // if file not chosen
    echo json_encode("ERROR: Please browse for a file before clicking the upload button.");
    exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
    echo json_encode("ERROR: Your file was larger than 5 Megabytes in size.");
    unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
    exit();
} else if (!preg_match("/.(gif|jpg|jpe|jpeg|png)$/i", $fileName) ) {
     // This condition is only if you wish to allow uploading of specific file types    
     echo json_encode("ERROR: Your image was not .gif, .jpg, .jpe, or .png.");
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
     exit();
} 
// END PHP Image Upload Error Handling ----------------------------------------------------
// Place it into your "uploads" folder mow using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, "../profiles/uploads/$fileName");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
    echo json_encode("ERROR: File not uploaded. Try again.");
    unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
    exit();
}
if  ($moveResult == true) {
    $db = mysqli_connect("localhost", "root", "password", "photos");
    $sql = "INSERT INTO user_images (images,date) VALUES ('$fileName',CURDATE())";
    mysqli_query($db, $sql);
    echo json_encode("Success: File uploaded.");

}
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
?>

Прежде чем я покажу вам весь свой реагирующий нативный код, я просто хочу сказать, что я незнаком, когда дело доходит до загрузки изображения в RN. Я прочитал много вопросов на SO, чтобы узнать, как это сделать, и посмотрел несколько видео на YouTube. Я не знаю, должен ли я использовать base64 (если кто-нибудь может мне это объяснить, это было бы здорово), насколько мне известно, я просто перетаскиваю путь к изображению, размер изображения и тип изображения, а затем вставляю это изображение. путь к моей папке и базе данных:

    SelectPhoto = () =>{
ImagePicker.openPicker({
cropping: true,
title: 'Select an image',
isCamera: true,
}).then((imgResponse) => {
  console.log(imgResponse);
  let imgSource = { uri: imgResponse[0].path.replace(/^.*[\\\/]/, '') };
  this.setState({
    userimgSource: imgSource,
    userimgSourceType: imgResponse[0].mime,
    userimgSourceSize: imgResponse[0].size,
  });
});


}

UploadPhoto = () =>{
  fetch('https://www.example.com/React/user-image-upload.php', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    userimgSource : this.state.userimgSource,
    userimgSourceType: this.state.userimgSourceType,
    userimgSourceSize: this.state.userimgSourceSize,

  })

  }).then((response) => response.json())
      .then((responseJson) => {

        // Showing response message coming from server after inserting records.
        Alert.alert(responseJson);


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

Вот тут и возникает путаница. Когда я console.log мой userimgSource: imgSource, userimgSourceType: imgResponse[0].mime, userimgSourceSize: imgResponse[0].size,, я действительно получаю правильные данные. Я получаю путь изображения: IMG_2018629.png, MIME: image/png и размер: 2,097,152. Есть ли причина, по которой PHP не может подобрать данные из того, что было дано в React Native?

1 Ответ

0 голосов
/ 02 июля 2018

Измените ваши заголовки на это

headers: {
    'Accept': '*',
    'Content-Type': 'multipart/form-data',
  }
  • Поскольку вы загружаете изображение, его тип контента не может быть 'Применение / JSON.

  • Поле заголовка запроса Accept можно использовать для указания определенных типов мультимедиа, которые приемлемы для ответа. Таким образом, добавление звездочки сделает ваш запрос на принятие ответа любого типа.

...