【发布时间】:2016-01-25 17:56:13
【问题描述】:
我正在制作一个允许用户将图片上传到服务器的 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;
}
保存照片.php:
<?php
$name = $_POST["name"];
$image = $_POST["image"];
$decodedImage = base64_decode("$image");
file_put_contents("pictures/" . $name . ".JPG", $decodedImage);?>
【问题讨论】:
-
请阅读 logcat 日志 ...
new Uri.Builder().appendQueryParameter("name", name).build()将抛出 UnsupportedOperationException ... 使用 Uri.Builder 不是我们通过 URLConnection API 发送 url 编码形式的方式 -
它没有抛出任何异常......我使用完全相同的代码将用户和密码数据发送到服务器,它的工作原理是由于某种原因它不适用于图片和我不知道为什么。
标签: android image upload server deprecated