如何将 base64 图像发送到服务器 - PHP


How to send base64 image to server - PHP

我正在通过PHP文件将base64字符串从Android应用程序发送到服务器。
我从教程视频中得到了这个:

<?php
    require 'Init.php';
    header('Content-type : bitmap; charset=utf8');
    if(isset($_POST['encoded_string'])){
        $encoded_string = $_POST['encoded_string'];
        $image_name = $_POST['image_name'];
        $decoded_string = base64_decode($encoded_string);
        $path = 'ProfileIcons/' .$image_name;
        $file = fopen($path, 'wb');
        $is_written = fwrite($file, $decoded_string);
        fclose($file);
    }
?>

它将图像存储在目录中,但当您打开时,它没有图像。这是一个空白的 png。代码有问题吗?如果是这样,我应该使用什么?谢谢。

您应该检查几点:

1.确保服务器已收到 base64 字符串

$encoded_字符串 = $_POST['encoded_string'];

检查$encoded_string的长度,它应该与安卓客户端所说的长度相同。

  1. 确保解码有效

    $decoded_字符串 = base64_decode($encoded_字符串);

检查$decoded_string的长度,它不应该是零或奇怪的。

  1. 确保写入的文件有效

    $is_write = fwrite($file, $decoded_string);

$is_written应该是已写入文件的数据的长度,如果是false,则有问题。