我正在尝试通过php脚本将用户个人资料图片从其画廊发送到在线文件系统。我已经确认,除了图片的名称和编码的字符串实际上没有从android应用程序发送到php脚本之外,其他所有操作均正常。我从脚本中获取了回显消息,并确认$ _POST值为空。
我已经确保要发送的信息,尤其是当将其发送到http请求时,其名称不为null。这是我的doInBackground,用于上传图片。 image是他们选择的图像的位图。
protected String doInBackground(String... strings) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT );
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("image", encodedImage));
dataToSend.add(new BasicNameValuePair("name", name));
HttpParams httpRequestParams = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS);
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
String result = "";
String connection = "http://www.myurl.com/uploadprofile.php";
try {
URL url = new URL(connection);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
InputStream ips = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, StandardCharsets.ISO_8859_1));
String line = "";
while ((line = reader.readLine()) != null) {
result += line;
}
reader.close();
ips.close();
http.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
这是php文件
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
$name = $_POST['name'];
$image = $_POST['image'];
$decodedImage = base64_decode("$image");
file_put_contents("uploads/".$name.".jpg", $decodedImage);
echo "entered this file: name-" . $name;
?>
我希望这会上传带有用户名的实际图片。但是,我只是得到一个空的.jpg文件。它应该是username.jpg,并且超过0个字节。