安卓向服务器端上传图片
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
}
;
@Override
protected String doInBackground(Void... voids) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, stream);
byte[] byte_arr = stream.toByteArray();
// Base64图片转码为String
encodedString = Base64.encodeToString(byte_arr, 0);
return null;
}
@Override
protected void onPostExecute(String s) {
SharedPreferences sp = MainActivity.this.getSharedPreferences("USER", Context.MODE_PRIVATE);
params.put("image", encodedString);
params.put("filename", sp.getString("telephone",null));
imageUpload();
}
}.execute(null, null, null);
}
public void imageUpload() {
String url = "http://192.168.1.102:8090/LBSTest/uploadimg";
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
Toast.makeText(getApplicationContext(), "upload success", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(int i,Header[] headers, byte[] bytes, Throwable throwable) {
if (i == 404) {
Toast.makeText(getApplicationContext(),
"Requested resource not found", Toast.LENGTH_LONG).show();
}
// 当 Http 响应码'500'
else if (i == 500) {
Toast.makeText(getApplicationContext(),
"Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// 当 Http 响应码 404, 500
else {
Toast.makeText(
getApplicationContext(), "Error Occured n Most Common Error: n1. Device " +
"not connected to Internetn2. Web App is not deployed in App servern3." +
" App server is not runningn HTTP Status code : "
+ i, Toast.LENGTH_LONG).show();
}
}
});
}
服务器端接受
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Utils.UploadImage;
@WebServlet("/uploadimg")
public class uploadimgLet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String imgEncodedStr = request.getParameter("image");
String fileName = request.getParameter("filename");
System.out.println(fileName+" "+imgEncodedStr);
if(imgEncodedStr != null){
UploadImage.convertStringtoImage(imgEncodedStr, fileName);
System.out.print("Image upload complete, Please check your directory");
} else{
System.out.print("Image is empty");
}
}
}
对数据进行转化为图片
public class UploadImage
{
public static void convertStringtoImage(String encodedImageStr, String fileName) {
try {
// Base64解码图片
byte[] imageByteArray = Base64.decodeBase64(encodedImageStr);
//
FileOutputStream imageOutFile = new FileOutputStream("E:/upload/" + fileName+".jpg");
imageOutFile.write(imageByteArray);
imageOutFile.close();
System.out.println("Image Successfully Stored");
} catch (FileNotFoundException fnfe) {
System.out.println("Image Path not found" + fnfe);
} catch (IOException ioe) {
System.out.println("Exception while converting the Image " + ioe);
}
}
}
服务器端配置访问图片
例如我的图片放在 /usr/local/include/image
打开tomcat的目录下 /conf/service.xml
加入<Context docBase="/usr/local/include/image" path="/pic" debug="0" reloadable="true"/>
保存编辑后,重新启动tomcat。
输入 http://ip:port/pic/图片名称.jpg 即可以访问当该图片。
安卓端图片的下载
private void showtp() {
new Thread(){
public void run() {
try {
//网络操作
URL url=new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int code = conn.getResponseCode();
if (code==200) {
InputStream is = conn.getInputStream();
Bitmap bitmap= BitmapFactory.decodeStream(is);
Message msg=new Message();
msg.what=SUCCESS;
msg.obj=bitmap;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg=new Message();
msg.what=ERROR;
handler.sendMessage(msg);
}
};
}.start();
private Handler handler =new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SUCCESS:
Bitmap bitmap=(Bitmap) msg.obj;
tp.setImageBitmap(bitmap);
break;
case ERROR:
Toast.makeText(MainActivity.this, "网络错误,请检查你的网路", 0).show();
break;
}
};
};