Android 通過(guò)Base64上傳圖片到服務(wù)器
創(chuàng)新互聯(lián)建站專(zhuān)注于企業(yè)成都營(yíng)銷(xiāo)網(wǎng)站建設(shè)、網(wǎng)站重做改版、欽北網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5場(chǎng)景定制、成都商城網(wǎng)站開(kāi)發(fā)、集團(tuán)公司官網(wǎng)建設(shè)、外貿(mào)營(yíng)銷(xiāo)網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁(yè)設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性?xún)r(jià)比高,為欽北等各大城市提供網(wǎng)站開(kāi)發(fā)制作服務(wù)。
之前做上傳圖片是采用HttpServlet上傳,不過(guò)用了一下Base64上傳圖片后,感覺(jué)比HttpServlet方便很多,大家也可以跟著嘗試一下。
前臺(tái)圖片處理:(傳Bitmap對(duì)象即可)
/** * 通過(guò)Base32將Bitmap轉(zhuǎn)換成Base64字符串 * @param bit * @return */ public String Bitmap2StrByBase64(Bitmap bit){ ByteArrayOutputStream bos=new ByteArrayOutputStream(); bit.compress(CompressFormat.JPEG, 40, bos);//參數(shù)100表示不壓縮 byte[] bytes=bos.toByteArray(); return Base64.encodeToString(bytes, Base64.DEFAULT); }
前臺(tái)發(fā)送數(shù)據(jù):(調(diào)用setImgByStr()方法,第一個(gè)參數(shù)imgStr 為Bitmap轉(zhuǎn)成Base64的字符串,第二個(gè)參數(shù)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(); // 設(shè)置網(wǎng)絡(luò)超時(shí)參數(shù) 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(Mapparams, 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); }
后臺(tái)接收數(shù)據(jù):
public void uploadPhoto() { //獲取存儲(chǔ)路徑 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); }
后臺(tái)圖片處理:
/** * 通過(guò)BASE64Decoder解碼,并生成圖片 * @param imgStr 解碼后的string */ public boolean string2Image(String imgStr, String imgFilePath) { // 對(duì)字節(jié)數(shù)組字符串進(jìn)行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) { // 調(diào)整異常數(shù)據(jù) b[i] += 256; } } // 生成Jpeg圖片 OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } }
OK ! 如果成功上傳前端會(huì)接收到true ,反之失敗false。希望對(duì)大家有所幫助!