我正在制作一个Android应用程序,允许用户将图片上传到服务器。代码有效,但由于不推荐使用HttpPost方法,我尝试更新解决方案,但更新后的解决方案不起作用。奇怪的是,同样更新的解决方案(具有不同的参数)是我用来登录用户的工具,它可以工作,所以我不知道错误是什么。谁知道我错过了什么?
更新的解决方案: 图片无法上传,但不会出现任何错误
@Override
protected Void doInBackground(Void... params) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
//PRUEBAS
try {
String urlSt = "http://phoenixcoding.tk/SavePicture.php";
URL url = new URL(urlSt);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("name", name)
.appendQueryParameter("image", encodedImage);
String query = builder.build().getEncodedQuery();
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
connection.connect();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
弃用的解决方案:它有效
@Override
protected Void doInBackground(Void... params) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);ArrayList<NameValuePair> dataToSend = new ArrayList<NameValuePair>();
dataToSend.add(new BasicNameValuePair("image", encodedImage));
dataToSend.add(new BasicNameValuePair("name", name));
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://phoenixcoding.tk/SavePicture.php");
try{
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
SavePhoto.php:
<?php
$name = $_POST["name"];
$image = $_POST["image"];
$decodedImage = base64_decode("$image");
file_put_contents("pictures/" . $name . ".JPG", $decodedImage);?>
答案 0 :(得分:1)
好吧,经过多次尝试,我终于成功了。我不知道原因,但在打开连接后添加输入流使图片上传。
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder str = new StringBuilder();
String strLine;
while ((strLine = reader.readLine()) != null) {
str.append(strLine + "\n");
}
is.close();