Android 는 Base 64 를 통 해 서버 에 그림 을 업로드 하여 인 스 턴 스 를 실현 합 니 다.

Android 는 Base 64 를 통 해 서버 에 사진 을 업로드 합 니 다.
기 존 에 올 린 사진 은 HttpServlet 으로 올 렸 는데 Base 64 로 올 린 사진 을 사용 해 보 니 HttpServlet 보다 훨씬 편리 한 것 같 아 요.여러분 도 따라 해 보 세 요.
프론트 이미지 처리:(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 에서 Base 64 로 전환 하 는 문자열 입 니 다.두 번 째 매개 변수 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 + "
"); } reader.close(); } return sb.toString(); } public static HttpResponse post(Map<String, Object> 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<NameValuePair> nameValuepairs = new ArrayList<NameValuePair>(); 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<String, Object> 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<String,Object> params = new HashMap<String, Object>(); 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; 
  } 
}   

OK ! 업로드 에 성공 하면 전단 이 true 로 받 아들 여지 고,반대로 실패 합 니 다 false.도움 이 됐 으 면 좋 겠 습 니 다!

좋은 웹페이지 즐겨찾기