前后台传图片,仅做个人记录

很久以前,自己仿开源中国,然后也搭了一个后台,那个时候,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();
}
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值