博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android 通过Base64上传图片到服务器
阅读量:6819 次
发布时间:2019-06-26

本文共 4796 字,大约阅读时间需要 15 分钟。

hot3.png

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

/**  * 通过Base32将Bitmap转换成Base64字符串  * @param bit  * @return  */  public String Bitmap2StrByBase64(Bitmap bit){     ByteArrayOutputStream bos=new ByteArrayOutputStream();     bit.compress(CompressFormat.JPEG, 40, bos);//参数100表示不压缩     byte[] bytes=bos.toByteArray();     return Base64.encodeToString(bytes, Base64.DEFAULT);  }

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

public static String host = "http://192.168.1.166:8080/ImageServer/";    public static String getContent(String url) throws Exception {        StringBuilder sb = new StringBuilder();        HttpClient client = new DefaultHttpClient();      HttpParams httpParams = client.getParams();      // 设置网络超时参数      HttpConnectionParams.setConnectionTimeout(httpParams, 3000);        HttpConnectionParams.setSoTimeout(httpParams, 5000);      HttpResponse response = client.execute(new HttpGet(url));      HttpEntity entity = response.getEntity();      if (entity != null) {          BufferedReader reader = new BufferedReader(new InputStreamReader(                  entity.getContent(), "UTF-8"), 8192);            String line = null;          while ((line = reader.readLine()) != null) {              sb.append(line + "\n");          }          reader.close();        }        return sb.toString();  }  public static HttpResponse post(Map
params, String url) { HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("charset", HTTP.UTF_8); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); HttpResponse response = null; if (params != null && params.size() > 0) { List
nameValuepairs = new ArrayList
(); for (String key : params.keySet()) { nameValuepairs.add(new BasicNameValuePair(key, (String) params .get(key))); } try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuepairs, HTTP.UTF_8)); response = client.execute(httpPost); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } } else { try { response = client.execute(httpPost); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return response; } public static Object getValues(Map
params, String url) { String token = ""; HttpResponse response = post(params, url); if (response != null) { try { token = EntityUtils.toString(response.getEntity()); response.removeHeaders("operator"); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return token; } public static Object setImgByStr(String imgStr,String imgName){ String url = host+"channel-uploadImage.action"; Map
params = new HashMap
(); params.put("imgStr", imgStr); params.put("imgName", imgName); return getValues(params, url); }

后台接收数据:

public void uploadPhoto() {      //获取存储路径      HttpServletRequest request = ServletActionContext.getRequest();      String path = ServletActionContext.getServletContext().getRealPath("/")+"upload";      File file = new File(path);      if(!file.exists()){          file.mkdir();      }      String imgPath  = path + request.getParameter("imgName");      String imgStr = request.getParameter("imgStr");      boolean flag = string2Image(imgStr, imgPath);      JacksonUtil.responseJSON(response, flag);  }

后台图片处理:

/**  * 通过BASE64Decoder解码,并生成图片  * @param imgStr 解码后的string  */  public boolean string2Image(String imgStr, String imgFilePath) {      // 对字节数组字符串进行Base64解码并生成图片      if (imgStr == null)          return false;      try {          // Base64解码          byte[] b = new BASE64Decoder().decodeBuffer(imgStr);          for (int i = 0; i < b.length; ++i) {              if (b[i] < 0) {                  // 调整异常数据                  b[i] += 256;              }          }          // 生成Jpeg图片          OutputStream out = new FileOutputStream(imgFilePath);          out.write(b);          out.flush();          out.close();          return true;      } catch (Exception e) {          return false;      }  }

转载于:https://my.oschina.net/yongqingfan/blog/724823

你可能感兴趣的文章
微信小程序录音实现
查看>>
remove namespace from xml config file
查看>>
<转>从SRCNN到EDSR,总结深度学习端到端超分辨率方法发展历程
查看>>
excel 获取中文拼音首字母
查看>>
Eclipse 使用maven创建Dynamic Web Project
查看>>
Python学习笔记——迭代器(RandSeq和AnyIter)
查看>>
MySQL索引使用方法和性能优化
查看>>
JSP简单练习-定时刷新页面
查看>>
JSON.parse()与JSON.stringify()的区别
查看>>
[Python] Boolean Or "Mask" Index Arrays filter with numpy
查看>>
有了#ifdef 为什么还需要#if defined
查看>>
eclipse中.properties文件不能输入中文的解决办法
查看>>
[Unit Testing] Mock a Node module's dependencies using Proxyquire
查看>>
C++中malloc/free和new/delete 的使用
查看>>
ASP.NET MVC读取XML并使用ViewData显示
查看>>
4.lists(双向链表)
查看>>
导入项目的时候报错Error:Could not find com.android.support.constraint:constraint-layout:1.0.0-alpha7...
查看>>
微服务(Microservices )简介
查看>>
.NET中的流
查看>>
在ASP.NET MVC 4中使用Kendo UI Grid
查看>>