Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

javascript - how can upload image using react js ajax and php?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...