douxun2023 2019-07-06 20:58
浏览 94
已采纳

使用PHP中的JSON和Image处理Http POST

I am creating an API to recieve and process data from phone app using PHP. I can successfully process most calls but, am struggling with how to receive POST with image and json in it.

I have the following code in my API.php file:

//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!');
}
  • 写回答

1条回答 默认 最新

  • doushuhuai7247 2019-07-06 21:21
    关注

    You can file a Base64 encoding and send it as a json field

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

    and function to decode

    function base64ToImage($base64String, $outputFile) {
        $file = fopen($outputFile, "wb");
        $data = explode(',', $base64String);
        fwrite($file, base64_decode($data[1]));
        fclose($file);
    
        return $outputFile;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog