首页 > 解决方案 > 如何使用 PHP REST API 和使用 JSON 格式的 REACT js 上传图像?

问题描述

我有一些用于基本CRUD 操作的完美PHP API,用户可以在其中创建、读取、更新和删除任何表单数据。现在我也想插入图像。我将REACT 用于客户端

所以我想修改我的“create_product”php API,以便它可以接受来自用户的JSON 编码数据(上传的 img)并将其插入数据库。以及每当调用 Read API 时它会显示产品图像的反向操作。

搜索了很多,但他们提供了其他解决方案,但也没有提供JSON格式或 API。我知道在 php 中上传图像的常规方法,但无法在 rest API 中弄清楚。

请任何人帮助我。我真的很感激。这是我的PHP API 代码

<?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// files needed to connect to database
include_once 'config/database.php';
include_once 'objects/product.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

// instantiate product object
$user = new Product($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));


// make sure data is not empty
if(
!empty($data->Name) &&
!empty($data->Price) &&
!empty($data->Description) &&
!empty($data->VehicleID)
) {

    // set product property values
    $user->Name = $data->Name;
    $user->Price = $data->Price;
    $user->Warranty = $data->Warranty;
    $user->Description = $data->Description;
    $user->Status = $data->Status;

    $user->SubCatPartID = $data->SubCatPartID;
    $user->VehicleID = $data->VehicleID;
    $user->VendorID = $data->VendorID;


  
    if ($user->create()) {

        http_response_code(200);

        echo json_encode(array("message" => "Spare Part Record is inserted Successfully"));
    } 
    else {

        http_response_code(400);

        echo json_encode(array("message" => "Unable to insert Spare Part... Sorry..."));
    }
}

else{
    http_response_code(400);
    echo json_encode(array("message" => "Unable to create product. Data is EMPTY."));
}

?>

这是 php create()方法:

class Product{

    // database connection and table name
    private $conn;
    private $table_name = "sparepart";

    // object properties
    public $SparePartID;
    public $Name;
    public $Price;
    public $Warranty;
    public $Description;
    public $Status;
    public $SubCatPartID;
    public $VehicleID;
    public $VendorID;


    public function __construct($db){
        $this->conn = $db;
    }

    function create(){

        // insert query
        $query = "INSERT INTO " . $this->table_name . "
            SET
                Name = :Name,
                Price = :Price,
                Warranty = :Warranty,
                Description = :Description,
                Status = :Status,
                SubCatPartID = :SubCatPartID,
                VehicleID = :VehicleID,
                VendorID = :VendorID";

        // prepare the query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->Name=htmlspecialchars(strip_tags($this->Name));
        $this->Price=htmlspecialchars(strip_tags($this->Price));
        $this->Warranty=htmlspecialchars(strip_tags($this->Warranty));
        $this->Description=htmlspecialchars(strip_tags($this->Description));
        $this->Status=htmlspecialchars(strip_tags($this->Status));

        $this->SubCatPartID=htmlspecialchars(strip_tags($this->SubCatPartID));
        $this->VehicleID=htmlspecialchars(strip_tags($this->VehicleID));

        $this->VendorID=htmlspecialchars(strip_tags($this->VendorID));

        $stmt->bindParam(':Name', $this->Name);
        $stmt->bindParam(':Price', $this->Price);
        $stmt->bindParam(':Warranty', $this->Warranty);
        $stmt->bindParam(':Description', $this->Description);
        $stmt->bindParam(':Status', $this->Status);
        $stmt->bindParam(':SubCatPartID', $this->SubCatPartID);
        $stmt->bindParam(':VehicleID', $this->VehicleID);
        $stmt->bindParam(':VendorID', $this->VendorID);

        if($stmt->execute()){
            return true;
        }

        return false;
    }

这是我在 REACT JS 中的 API 调用(用于创建产品):

  onSubmit (e)
  {
    e.preventDefault();
    const sparepart = {
      Name: this.state.Name,
      Price: this.state.Price,
      Warranty: this.state.Warranty,
      Description: this.state.Description,
      Status: this.state.Status,
      SubCatPartID: this.state.SubCatPartID,
      VehicleID: this.state.VehicleID,

      VendorID: this.state.vendor.VendorID }


  axios.post('http://localhost/Auth/api/insert_parts.php', sparepart)
  .then((result) => {
    console.log(result.data);
    alert("Congratulations! New Spare Part has been added!");
    this.setState({redirectToReferrer: true});
    return result;
   })
   .catch(error => {
   if (error) {
     console.log("Sorry cannot insert data");
   console.log(error);  }
     });
   }

标签: phpjsonreactjsapifile-upload

解决方案


我的 PHP 不是很好,所以我会尝试彻底解释我的答案,因为我不能举个例子。在 React 中,您可以使用input标签 withtype="file"来接受图像并将其设置为 React 组件的状态。完成后,您可以使用FileReader类读取文件并返回 Base64 字符串。然后你所要做的就是在你当前的 JSON 输入中为字符串添加另一个标签,然后一次性发送!确保在 PHP 中允许多部分,因为图像对于一个数据包来说可能太大了。


推荐阅读