很久以前,自己仿开源中国,然后也搭了一个后台,那个时候,Android端图片上传倒还好,后台取出就有点麻烦了。
后来采取图片转流转base64 string的形式搞定了。
(最近清理代码库,本文仅做个人记录,见谅)
涉及
base64
流
流程
从相册取得bitmap文件(或者直接拍照)
bitmap转byte
byte转string
string放入request里请求
后台取出string
string转byte
byte通过两个输出流转服务器文件
http://blog.csdn.net/lincyang/article/details/46596899
前台传递
if (imagePath != null) {
//取得bmp位图
Bitmap bm_profile = BitmapFactory.decodeFile(imagePath);
//bmp位图转成byte
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm_profile.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
//base64 encode转成String
byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
String encodeString = new String(encode);
//上传
String userName = getActivity()
.getSharedPreferences("xbh", MODE_PRIVATE)
.getString("userName", "");
String url = "/Oschina/LoginServlet?username=" + userName + "&order=replaceProfile";
Request request = ItheimaHttp.newPostRequest(url);
//放在request里上传
request.putParams("bm_profile", encodeString);
Call call = ItheimaHttp.send(request, new HttpResponseListener<User>() {
@Override
public void onResponse(User user) {
}
});
} else {
toast("无法取得照片");
}
后台取出
//这里是从照相机或者相册中选取图片作为新头像
else if(order.equals("replaceProfile")) {
Base64 base64 = new Base64();
byte[] decode = base64.decode(bm_profile);//图片流
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File ("D:\\apache-tomcat-9.0.1\\webapps\\Oschina");
if (!dir.exists()&&dir.isDirectory()) {
dir.mkdirs();
}
file = new File("D:\\apache-tomcat-9.0.1\\webapps\\Oschina" + "\\" + userName+".jpg");
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(decode);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos !=null ) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos !=null ) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}