简体   繁体   English

将Base64编码图像上传到php服务器

[英]Uploading A Base64 encode Image to php server

how do i upload a Base64 encoded image to a PHP server using HttpURLConnection? 如何使用HttpURLConnection?Base64编码的图像上传到PHP服务器HttpURLConnection? All the answers i have seen so far are based on HttpClient which no longer exists. 到目前为止,我所看到的所有答案都基于不再存在的HttpClient I got a httprequest.java library that sends post request to the server, the problem i have with it is that the image string at the server-side is always different to the one i send. 我有一个httprequest.java库,它将发布请求发送到服务器,但我遇到的问题是server-side的图像字符串始终不同于我发送的图像字符串。

This is my code so far. 到目前为止,这是我的代码。

HttpRequest request = new HttpRequest(Konstants.address+Konstants.save_image);
        request.prepare(HttpRequest.Method.POST);
        String encodedImage = Base64.encodeToString(image, Base64.URL_SAFE);
        //image is a byte[] with image data
        HashMap<String, String>map = new HashMap<>();
        map.put("username",username);
        map.put("image", encodedImage);
        Log.d("IMAGE-DATA", encodedImage);

        request.withData(map);
        JSONObject object = request.sendAndReadJSON();

        code = object.getInt("response_code");
        if (code == 0)
            flag = Boolean.FALSE;
        String s = object.getString("response_message");
        Log.d("SERVER-REPLY", s);
        //encodedImage and s are different

and the PHP code below: 以及下面的PHP代码:

<?php
  if(!$_SERVER['REQUEST_METHOD']=='POST'){
     $response["response_code"] = 0;
     $response["response_message"] = "INVALID REQUEST";
     die(json_encode($response));
  }
 if (empty($_POST)) {
    $response["response_code"] = 0;
    $response["response_message"] = "One or both of the fields are empty .";
    die(json_encode($response));
 }

$username1 = urldecode($_POST['username']); 
$data = $_POST['image'];
$binary = base64_decode($data);

list($path, $tmp) = explode(".", $username1);

$success = file_put_contents("./images/$path.png", $binary);
if ($success){
    $response["response_message"]=$data;
    $response["response_code"] = 1;
}else{
    $response["response_message"]="failure";
    $response["response_code"] = 0;
}

echo json_encode($response);
?>

Look into the differences. 研究差异。 Sometimes you need to replace spaces with plusses. 有时您需要用加号替换空格。

$binary = base64_decode(str_replace(" ", "+", $_POST['image']));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM