首页 > 解决方案 > 在 PHP 中使用 JSON 和图像处理 Http POST

问题描述

我正在创建一个 API 来使用 PHP 从手机应用程序接收和处理数据。我可以成功处理大多数呼叫,但是正在努力解决如何接收带有图像和 json 的 POST。

我的 API.php 文件中有以下代码:

//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
    throw new Exception('Request method must be POST!');
}

//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
    throw new Exception('Content type must be: application/json');
}

//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));

//Attempt to decode the incoming RAW post data from JSON.
$json = json_decode($content, true); 

//If json_decode failed, the JSON is invalid.
if(!is_array($json)){
    throw new Exception('Received content contained invalid JSON!');
}

标签: phpjson

解决方案


您可以归档 Base64 编码并将其作为 json 字段发送

$path = 'image.png';
$info = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

和解码功能

function base64ToImage($base64String, $outputFile) {
    $file = fopen($outputFile, "wb");
    $data = explode(',', $base64String);
    fwrite($file, base64_decode($data[1]));
    fclose($file);

    return $outputFile;
}

推荐阅读