如何上传图片到主机?

时间:2019-07-12 06:42:56

标签: php

我想将信息发送到android中的服务器。我编写了一个Web服务,但没有用,并返回此错误:

  

无法打开流

在android studio中,图像会转换为String B64并发送到Web服务。然后,在Web服务中对图像进行解码。有时会返回以下回声:

  

数据空

我该如何解决?

我的PHP代码(Web服务):

<?php

require_once('conn.php');

$upload_path = '../user_images/';
$server_ip = gethostbyname(gethostname());
$upload_url = 'http://' . $server_ip . '/' . $upload_path;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['name']) and isset($_POST['phone'])
        and isset($_POST['image']) and isset($_POST['email'])
        and isset($_POST['password'])) {

        $name = $_POST['name'];
        $phone = $_POST['phone'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $image_address = "http://MY_HOST/game/user_images/" . 'IMG_' . $phone . '.png';


        if (upload_file($_POST['image'], $phone)) {

            $sql = "insert into users (phone,name,picture,email,password) values ('$phone','$name', '$image_address' ,'$email','$password')";

            if (mysqli_query($con, $sql)) {

                echo json_encode(array('status' => 1, 'message' => "information saved"));
            } else

                echo json_encode(array('status' => 0, 'message' => "error in connection with database"));

        } else
            echo json_encode(array('status' => 0, 'message' => "error in upload image"));


    } else echo json_encode(array('status' => 0, 'message' => "DATA EMPTY"));
}

function upload_file($encoded_string, $phone)
{
    $decoded_file = base64_decode($encoded_string);
    $file_dir = "http://MY_HOST/game/user_images/" . 'IMG_' . $phone . '.png';
    try {
        if (file_put_contents($file_dir, $decoded_file))
            return true;
        else return false;
    } catch (Exception $e) {
        return false;
    }
} ?>

0 个答案:

没有答案