upload image with reactjs and php

Viewed 52

I can upload my record with an image to the "mysql" database without any problem, but the image is being saved directly in the mysql database and what I need is for the path and the path to be saved in the database. some folder the image, but I can not do it, sent my source code.

Note: the code I have works but it is saving the image directly in mysql and what I need is for it to save the path and the image in a folder as such.

proyecto.js "react.js"

import React,{useState} from 'react';
import axios from 'axios';

function Esquemas() {

    const [nombre, setNombre] = useState('');
    const [imagen2, setImagen2] = useState(null);
    const [id, setId] = useState(''); 
    const [bandera, setBandera] = useState(true);

 async function addProducto(e) {
    let fd = new FormData() 
    fd.append("imagen2", imagen2)
    fd.append("nombre", nombre)
    const res = await axios.post('https://miweb.com/esquema/', fd);
    console.log(res.data)
 
   } 
 
async function UpdateProducto(e) {
      const obj = {id, nombre};
      const res = await axios.put('https://miweb.com/esquema/', obj);
      console.log(res.data) 
  }
  
 function addUpdate(e) {
      e.preventDefault(); 
      bandera? addProducto():UpdateProducto();
  }
  
    return (
      <div className="content-wrapper">

    <section className="content">
<div class="card card-primary">

<form>
<div class="card-body">
<div class="form-group">
<label for="exampleInputEmail1">Título</label>

<input type="text" placeholder="Título proyecto" className="form-control"
                 onChange={(e) => setNombre(e.target.value)}
                 value={nombre}/>
</div>

<div class="form-group">
<label for="exampleInputFile">Imagenes</label>
<div class="input-group">
<div class="custom-file">
<input type="file" class="form-control-file" className='btn btn-success' multiple
 accept="image/*" onChange={(e) => setImagen2(e.target.files[0])}
/>
<label class="custom-file-label" for="exampleInputFile">Clic</label>
</div>
<div class="input-group-append">
<span class="input-group-text">Subir</span>
</div>
</div>
</div>

</div>

<div class="card-footer">

<button  className="btn btn-primary" 
               onClick={(e) => addUpdate(e)} >
                 {bandera?"CREAR ESQUEMA":"Edit"}
                </button> 
</div>
<br/>
</form>
    </div>  
    </section>
</div>
    )
    }
   
export default Esquemas

index.php

<?php
require_once('conexion.php');
require_once('api.php');
require_once('cors.php');
$method = $_SERVER['REQUEST_METHOD'];

if($method == "GET") {
    if(!empty($_GET['id'])){
      $id = $_GET['id'];  
      $api = new Api();
      $obj = $api->getProducto($id);
      $json = json_encode($obj);
      echo $json;     

    }else{
      $vector = array();
      $api = new Api();
      $vector = $api->getProductos();
      $json = json_encode($vector);
      echo $json;
    }
}

if($method=="POST"){
    $json = null;
    $imagen2 = (file_get_contents($_FILES['imagen2']['tmp_name']));
    $nombre = $_POST['nombre'];
    $api = new Api();
    $json = $api->addProducto($nombre, $imagen2);
    echo $json;
}


?>

api.php

<?php

class Api{

public function getProductos(){

   $vector = array();
   $conexion = new Conexion();
   $db = $conexion->getConexion();
   $sql = "SELECT * FROM producto";
   $consulta = $db->prepare($sql);
   $consulta->execute();
   while($fila = $consulta->fetch()) {
       $vector[] = array(
         "id" => $fila['id'],
         "nombre" => $fila['nombre']
         }//fin del ciclo while 

   return $vector;
}

public function getProducto($id){

  $vector = array();
  $conexion = new Conexion();
  $db = $conexion->getConexion();
  $sql = "SELECT * FROM producto WHERE id=:id";
  $consulta = $db->prepare($sql);
  $consulta->bindParam(':id', $id);  
  $consulta->execute();
  while($fila = $consulta->fetch()) {
      $vector[] = array(
        "id" => $fila['id'],
        "nombre" => $fila['nombre'],
         "imagen2" =>  base64_encode($fila['imagen2']));
        }//fin del ciclo while 

  return $vector[0];
}


public function addProducto($nombre, $imagen2){
  
  $conexion = new Conexion();
  $db = $conexion->getConexion();
  $sql = "INSERT INTO producto (nombre, imagen2) VALUES (:nombre,:imagen2)";
  $consulta = $db->prepare($sql);
  $consulta->bindParam(':nombre', $nombre);
  $consulta->bindParam(':imagen2', $imagen2);
  $consulta->execute();

  return '{"msg":"producto agregado"}';
}

}

?>

0 Answers
Related