php - 在 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!');
}
解决方案
您可以归档 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;
}
推荐阅读
- python - 如何在 Kivy 中使用创建圆形或圆形按钮。Kv 和不使用。.kv 文件
- c# - 如何在弹出窗口中单击按钮?(木偶锋利)
- c# - 无法安装 VS2019 软件并抛出“Microsoft.VisualCpp.Redist.14”错误
- java - 在 Jenkins 中运行构建时,我收到“java/lang/OutOfMemoryError”
- javascript - 我可以打开 cy.wait() 超时而不是断言失败吗?
- c - Linux 多播数据包在 4 分钟后干涸
- python - 在 PyQt 的第二个线程中打开子对话框的正确方法是什么?
- java - 如何为给定的 maven 或 gradle 项目生成已弃用的库列表?
- c# - 使用派生类时如何使用 Fluent Assertion Should().BeEquivalentTo() 检查等价性
- tensorflow - 在 tensorflow 中显示 CUDA 运行时版本