zoukankan      html  css  js  c++  java
  • Android 通过Base64上传图片到服务器

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

     

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

    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

    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 + " ");  
    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. }  

    后台接收数据:

    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. }  

    后台图片处理:

    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。希望对大家有所帮助!

  • 相关阅读:
    TDengine 基本操作
    Spark 提交运行 保存结果 流程控制
    Redis 分布式锁
    Linux 基础命令
    HIVE 分桶模式
    EX: 这里是收集的面试题
    使用python批量创建 mysql 表
    Navicat写MySQL触发器,用来同步表
    NXOpen 创建体获取所有边、边端点信息,过虑竖边倒圆水平边倒角
    NXOpen遍历实体移除参数和改色
  • 原文地址:https://www.cnblogs.com/cuihongyu3503319/p/5155330.html
Copyright © 2011-2022 走看看