doudou8081 2019-03-30 10:18
浏览 109
已采纳

如何使用PHP REST API和REACT js使用JSON格式上传图像?

I have some perfectly working PHP APIs for basic CRUD operations where user can create, read, update and delete any form data. Now I want to insert images as well. I use REACT for client side.

So I want to modify my "create_product" php APIs so that it can accept the JSON encoded data(uploaded img) from user and insert it in Database. and Also the reverse action where it will Show the image of a product whenever Read API is called.

I searched this alot but they give other solutions but nor with JSON format or API. i know regular way to upload image in php but cannot figure it out in rest API.

PLEASE ANYONE HELP ME. I would be really THANKFUL. here is my PHP API code:

<?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."));
}

?>

here is the php create() method:

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;
    }

And here is my API call in REACT JS (to create product):

  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);  }
     });
   }

</div>

展开全部

  • 写回答

1条回答 默认 最新

  • douzhi9478 2019-03-30 14:41
    关注

    My PHP is not great, so I'll try to explain my answer thoroughly since I can't give an example. In React, you can use an input tag with type="file" to accept images and set it to the React component's state. Once done, you can use the FileReader class to read the file and have return a Base64 string. Then all you have to do is add another tag in your current JSON input for the string and send it along all at once! Make sure to allow multipart in PHP since the image might be too big for one packet.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部