【发布时间】:2018-06-30 01:09:04
【问题描述】:
我花了一段时间才弄清楚,因为在应用程序屏幕上我得到的只是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
?>
在我向你展示我所有的 react native 代码之前,我只想说我对 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 中获取数据是否有原因?
【问题讨论】:
-
你在这里混合了两件事。只有当 POST 正文包含使用 Content-Type
multipart/form-data(标准 MIME 格式)发布的文件时,PHP 才会填充$FILES。但是,您正在发送 JSON(在 PHP 中,您还期望通过file_get_contents('php://input')发送 JSON POST 数据)。因此,要么删除$FILES的使用并将图像作为 Base64 编码的 JSON 字符串发布,要么使用真正的multipart/form-data(我认为这是更可取的,因为它允许您在不转换的情况下发布二进制数据并允许您使用内置 PHP文件处理)。 -
请参阅stackoverflow.com/a/26261002/11940 了解有关如何真正防止
$HTTP_RAW_POST_DATA被填充的更多信息:如消息所示,在php.ini 中将always_populate_raw_post_data设置为-1。将其设置为关闭或 0 只会阻止已知Content-Types的 POST(显然,application/json不是其中之一)。 -
抱歉,我指的是
$_FILES,而不是$FILES。
标签: php mysql react-native fetch image-uploading