如何使用Base64
将PHP
编码的图像上载到HttpURLConnection?
服务器,到目前为止,我所看到的所有答案都基于不再存在的HttpClient
。我有一个httprequest.java
库,它将发布请求发送到服务器,但我遇到的问题是server-side
处的图像字符串始终与我发送的图像字符串不同。
到目前为止,这是我的代码。
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
和下面的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);
?>
答案 0 :(得分:0)
研究差异。有时您需要用加号替换空格。
$binary = base64_decode(str_replace(" ", "+", $_POST['image']));