i am trying to upload an image to folder. am using react.js as the front end. I have written the connection between react and php using Ajax. For the back end am using Php. am able to acces my input variables when i do console logss
import React,{useState, useEffect} from 'react';
export const Photo = () => {
const[picture,setPicture]=useState("");
const[productId,setProductId]=useState("id");
const postPicture=(e)=>{
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/imran/photo.php', true);**strong text**
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
console.log(xhr.setRequestHeader)
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send(`productId=${productId}&picture=${picture}`);
}
const handleUpload=(event)=> {
setPicture(event.target.files[0]);
console.log(picture);
}
return (
<>
<input
placeholder="picture"
type="file"
onChange={handleUpload}
/><br/>
<input
value={productId}
placeholder="product id"
type="hidden"
onChange={(event) => {
setProductId(event.target.value);
}}
/>
<button onClick={postPicture}>Add Employee</button>
</>
)
}
my php code is as follows:
<?php
header('Access-Control-Allow-Origin:*');
$conn = mysqli_connect('localhost', 'root', '', 'imran');
$productId = mysqli_real_escape_string($conn, $_POST['productId']);
$currentDir = getcwd();
$uploadDirectory = "/public/pictures/";
$errors = [];
$fileExtensions = ['jpeg','jpg','png','gif'];
$fileName = $_FILES['picture']['name'];
$fileTmpName = $_FILES['picture']['tmp_name'];
$fileType = $_FILES['picture']['type'];
$fileExtension = strtolower(pathinfo($fileName,PATHINFO_EXTENSION));
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
if (isset($fileName)) {
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "JPEG, JPG, PNG and GIF images are only supported";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo "The image " . basename($fileName) . " has been uploaded.";
echo $productId;
} else {
echo "An error occurred while uploading. Try again.";
}
} else {
foreach ($errors as $error) {
echo $error . "The following error occured: " . "
";
}
}
}
?>
when i submit i get the response
<b>Notice</b>: Undefined index: picture in <b>C:xampphtdocsimranphoto.php</b> on line <b>18</b><br />
i cant really tell what i have done wrong.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…