[英]Upload image to server from android app not working
I'm trying to write the code to upload images from android app to the server using php.我正在尝试编写代码以使用 php 将图像从 android 应用程序上传到服务器。 I'm attempting to do it by convert it to Base64 and send it as String我试图通过将其转换为 Base64 并将其作为字符串发送
This is the java code:这是Java代码:
public class uploadImage extends AsyncTask< String, String, String>{
Bitmap _image;
uploadImage(Bitmap image){
_image = image;
}
@Override
protected String doInBackground(String... params) {
HttpURLConnection con = null;
BufferedOutputStream os= null;
try {
URL url = new URL("URL_TO_SERVER");
con = (HttpURLConnection) url.openConnection();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
_image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byte_arr = byteArrayOutputStream.toByteArray();
String _imageEncoded = Base64.encodeToString(byte_arr, Base64.DEFAULT);
JSONObject jsonObject = new JSONObject();
jsonObject.put("imageEncoded", _imageEncoded);
String message = jsonObject.toString();
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
con.setRequestProperty("X-Requested-With", "XMLHttpRequest");
con.connect();
os = new BufferedOutputStream(con.getOutputStream());
os.write(message.getBytes());
os.flush();
return "";
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
finally {
if (con != null)
con.disconnect();
if (os != null)
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}//uploadImage
This is the php code:这是php代码:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
$imageEncoded = $obj->{"imageEncoded"}
$image = base64_decode("$imageEncoded");
$alterName = rand();
$target= $_SERVER['DOCUMENT_ROOT']."/imagenes/";
$new_img_path =$target.$alterName.".jpg";
file_put_contents( $new_img_path, $image );?>
For some reason it just doesn't work, could someone tell me what is my error please?由于某种原因它不起作用,有人可以告诉我我的错误是什么吗? or guide me in a better approach.或以更好的方法指导我。
Use following class "Base64":使用以下类“Base64”:
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
yourBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
byte[] bArray = outStream.toByteArray();
String imgEncoding = Base64.encodeBytes(bArray);
Here is the link to that class:这是该课程的链接:
https://sourceforge.net/projects/iharder/files/base64/2.3/Base64-v2.3.7.zip/download https://sourceforge.net/projects/iharder/files/base64/2.3/Base64-v2.3.7.zip/download
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.