Android 通过Base64上传图片到服务器

116 篇文章 0 订阅

http://blog.csdn.net/h7870181/article/details/19971557

之前做上传图片是采用HttpServlet上传,不过用了一下Base64上传图片后,感觉比HttpServlet方便很多,大家也可以跟着尝试一下。


前台图片处理:(传Bitmap对象即可)

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 通过Base32将Bitmap转换成Base64字符串 
  3.  * @param bit 
  4.  * @return 
  5.  */  
  6. public String Bitmap2StrByBase64(Bitmap bit){  
  7.    ByteArrayOutputStream bos=new ByteArrayOutputStream();  
  8.    bit.compress(CompressFormat.JPEG, 40, bos);//参数100表示不压缩  
  9.    byte[] bytes=bos.toByteArray();  
  10.    return Base64.encodeToString(bytes, Base64.DEFAULT);  
  11. }  


前台发送数据:(調用setImgByStr()方法,第一個參數imgStr 为Bitmap转成Base64的字符串,第二个参数imgName为图片的名字,包含后缀名.jpg

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static String host = "http://192.168.1.166:8080/ImageServer/";  
  2.   
  3. public static String getContent(String url) throws Exception {  
  4.   
  5.     StringBuilder sb = new StringBuilder();  
  6.   
  7.     HttpClient client = new DefaultHttpClient();  
  8.     HttpParams httpParams = client.getParams();  
  9.     // 设置网络超时参数  
  10.     HttpConnectionParams.setConnectionTimeout(httpParams, 3000);  
  11.   
  12.     HttpConnectionParams.setSoTimeout(httpParams, 5000);  
  13.     HttpResponse response = client.execute(new HttpGet(url));  
  14.     HttpEntity entity = response.getEntity();  
  15.     if (entity != null) {  
  16.         BufferedReader reader = new BufferedReader(new InputStreamReader(  
  17.                 entity.getContent(), "UTF-8"), 8192);  
  18.   
  19.         String line = null;  
  20.         while ((line = reader.readLine()) != null) {  
  21.             sb.append(line + "\n");  
  22.         }  
  23.         reader.close();  
  24.   
  25.     }  
  26.   
  27.     return sb.toString();  
  28. }  
  29. public static HttpResponse post(Map<String, Object> params, String url) {  
  30.   
  31.     HttpClient client = new DefaultHttpClient();  
  32.     HttpPost httpPost = new HttpPost(url);  
  33.     httpPost.addHeader("charset", HTTP.UTF_8);  
  34.     httpPost.setHeader("Content-Type",  
  35.             "application/x-www-form-urlencoded; charset=utf-8");  
  36.     HttpResponse response = null;  
  37.     if (params != null && params.size() > 0) {  
  38.         List<NameValuePair> nameValuepairs = new ArrayList<NameValuePair>();  
  39.         for (String key : params.keySet()) {  
  40.             nameValuepairs.add(new BasicNameValuePair(key, (String) params  
  41.                     .get(key)));  
  42.         }  
  43.         try {  
  44.             httpPost.setEntity(new UrlEncodedFormEntity(nameValuepairs,  
  45.                     HTTP.UTF_8));  
  46.             response = client.execute(httpPost);  
  47.         } catch (UnsupportedEncodingException e) {  
  48.             e.printStackTrace();  
  49.         } catch (ClientProtocolException e) {  
  50.             e.printStackTrace();  
  51.         } catch (IOException e) {  
  52.             e.printStackTrace();  
  53.         } catch (RuntimeException e) {  
  54.             e.printStackTrace();  
  55.         }  
  56.     } else {  
  57.         try {  
  58.             response = client.execute(httpPost);  
  59.         } catch (ClientProtocolException e) {  
  60.             e.printStackTrace();  
  61.         } catch (IOException e) {  
  62.             e.printStackTrace();  
  63.         }  
  64.     }  
  65.   
  66.     return response;  
  67.   
  68. }  
  69. public static Object getValues(Map<String, Object> params, String url) {  
  70.     String token = "";  
  71.     HttpResponse response = post(params, url);  
  72.     if (response != null) {  
  73.         try {  
  74.             token = EntityUtils.toString(response.getEntity());  
  75.             response.removeHeaders("operator");  
  76.         } catch (ParseException e) {  
  77.             e.printStackTrace();  
  78.         } catch (IOException e) {  
  79.             e.printStackTrace();  
  80.         }  
  81.     }  
  82.     return token;  
  83. }  
  84. public static Object setImgByStr(String imgStr,String imgName){  
  85.     String url =  host+"channel-uploadImage.action";  
  86.     Map<String,Object> params = new HashMap<String, Object>();  
  87.     params.put("imgStr", imgStr);  
  88.     params.put("imgName", imgName);  
  89.     return getValues(params, url);  
  90. }  


后台接收数据:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void uploadPhoto() {  
  2.     //获取存储路径  
  3.     HttpServletRequest request = ServletActionContext.getRequest();  
  4.     String path = ServletActionContext.getServletContext().getRealPath("/")+"upload";  
  5.     File file = new File(path);  
  6.     if(!file.exists()){  
  7.         file.mkdir();  
  8.     }  
  9.     String imgPath  = path + request.getParameter("imgName");  
  10.     String imgStr = request.getParameter("imgStr");  
  11.     boolean flag = string2Image(imgStr, imgPath);  
  12.     JacksonUtil.responseJSON(response, flag);  
  13. }  


后台图片处理:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 通过BASE64Decoder解码,并生成图片 
  3.  * @param imgStr 解码后的string 
  4.  */  
  5. public boolean string2Image(String imgStr, String imgFilePath) {  
  6.     // 对字节数组字符串进行Base64解码并生成图片  
  7.     if (imgStr == null)  
  8.         return false;  
  9.     try {  
  10.         // Base64解码  
  11.         byte[] b = new BASE64Decoder().decodeBuffer(imgStr);  
  12.         for (int i = 0; i < b.length; ++i) {  
  13.             if (b[i] < 0) {  
  14.                 // 调整异常数据  
  15.                 b[i] += 256;  
  16.             }  
  17.         }  
  18.         // 生成Jpeg图片  
  19.         OutputStream out = new FileOutputStream(imgFilePath);  
  20.         out.write(b);  
  21.         out.flush();  
  22.         out.close();  
  23.         return true;  
  24.     } catch (Exception e) {  
  25.         return false;  
  26.     }  
  27. }     

OK ! 如果成功上传前端会接收到true ,反之失败false。希望对大家有所帮助!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值