我开发了一个PHP项目,现在我正在将其连接到react原生应用程序。然而,我尝试了许多代码将图像上传到服务器,但都不起作用。
这是我的代码示例
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');
}
};
对于PHP服务器端(upload.PHP(,以下是代码
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."
)
);
}
}
我从这里得到这个代码https://aboutreact.com/file-uploading-in-react-native/
我得到
这个错误
有人能帮我吗?任何替代方案都可以。
编辑:
基于@Sadia Chaudhary代码,此函数可用于
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');
}
};
该错误与图像上传无关。由于response.json()
,您正面临此错误。另外,尝试像这样转换图像。
//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}`
});