Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發怎麼少得了後端(下):圖片的 Base64 上傳與存儲

編輯:關於 Android 程式設計

前面我們講了如何請求服務器、如何往數據庫存簡單數據,但大家都清楚,一個 App 不可能只有文字,還會有圖片等一系列複雜數據。今天就用注冊場景,講講如何把頭像圖片一起上傳到服務器、數據庫又該怎麼存。

圖片既可以作為文件上傳,也可以作為流上傳,還可以作為 Base64 編碼上傳。這裡選擇簡單一點的方案——Base64 編碼上傳,也就是先把圖片轉成 Base64 編碼字符串再上傳,數據庫中保存的是字符類型。話不多說,直接看例子。

1. 新建一個圖片上傳的 Servlet

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Content-Type", "text/html;charset=UTF-8"); //設置頭部的編碼,防止中文亂碼 String username = request.getParameter("username"); String password = request.getParameter("password"); String userhead = request.getParameter("userhead"); // 判空 if (username == null || username.equals("") || password == null || password.equals("") || userhead == null || userhead.equals("")) { return; } // 請求數據庫 DBUtils dbUtils = new DBUtils(); dbUtils.openConnect(); BaseBean bean = new BaseBean(); RegisterBean data = new RegisterBean(); String imageName = TimeUtils.getNowTime() + ".jpg"; // 以當前時間作為圖片名,具有唯一性 System.out.println(getServletContext().getRealPath("/images")); String path = getServletContext().getRealPath("/images/" + imageName); // 圖片的絕對路徑(保存在apache服務器的某個文件夾目錄下) if (!Base64Utils.GenerateImage(userhead, path)) { // 判斷圖片是否保存成功 bean.setCode(-2); bean.setData(data); bean.setMsg("圖片出錯!!"); } else if (dbUtils.isExistInDB(username)) { bean.setCode(-1); bean.setData(data); bean.setMsg("該賬號已存在"); } else if (!dbUtils.insertDataToDB(username, password, imageName)) { //判斷注冊是否成功 bean.setCode(0); bean.setMsg("注冊成功!!"); data.setUsername(username); data.setPassword(password); data.setToken(TokenUtils.getToken(username, password)); bean.setData(data); } else { bean.setCode(500); bean.setData(data); bean.setMsg("數據庫錯誤"); } Gson gson = new Gson(); String json = gson.toJson(bean); try { response.getWriter().println(json);// 將json數據傳給客戶端 } catch (Exception e) { e.printStackTrace(); } finally { response.getWriter().close(); // 關閉這個流,不然會發生錯誤的 } dbUtils.closeConnect(); // 關閉數據庫連接 } 

稍微解釋一下:這裡在客戶端把圖片轉成 Base64 編碼,服務器端再把編碼還原成圖片,保存在服務器的某個文件夾下(可以自定義,但必須在該工程下的某個目錄,用 getServletContext().getRealPath() 獲取),最後把圖片名與服務器地址拼接後存進數據庫。可能有人會問:為什麼不把圖片直接存進數據庫?可以是可以,但數據庫存取的容量有限,直接存可能導致圖片出錯甚至數據庫崩掉。

DBUtils 的代碼:

 public boolean insertDataToDB(String username, String password, String userhead) { String token = TokenUtils.getToken(username, password); //token可以自己按照自己的意願生成一下 System.out.println("path------->" + userhead); String imagePath = "https://192.168.1.101:8080/MyWeb/images/" + userhead; //這裡做了一個地址拼接的過程,將這個圖片最終的地址保存到數據庫 try { sta = conn.createStatement(); String sql = " insert into userinfo ( user_name , user_pwd , token , user_head ) values ( " + "'" + username + "', " + "'" + password + "', " + "'" + token + "', " + "'" + imagePath + "' )"; return sta.execute(sql); } catch (SQLException e) { e.printStackTrace(); } return false; } 

再奉上 Base64 的編碼解碼代碼:

  /** * bitmap轉base64(客戶端用) * * @param bitmap * @return */ public static String bitmapToBase64(Bitmap bitmap) { String result = null; ByteArrayOutputStream baos = null; try { if (bitmap != null) { baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); baos.flush(); baos.close(); byte[] bitmapBytes = baos.toByteArray(); result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (baos != null) { baos.flush(); baos.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } /** * 對字節數組字符串進行Base64解碼並生成圖片(服務端用) * * @param imgStr * @param imgFilePath * @return */ public static boolean GenerateImage(String imgStr, String imgFilePath) { if (imgStr == null) // 圖像數據為空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解碼 byte[] bytes = decoder.decodeBuffer(imgStr); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 調整異常數據 bytes[i] += 256; } } // 生成jpeg圖片 OutputStream out = new FileOutputStream(imgFilePath); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } 

服務端寫好了,去客戶端測一把

布局咱們就簡單一點,請求還是沿用上次演示的 asynchttpclient:

 public void requestHost(){ if (CygStringUtil.isEmpty(CygStringUtil.getEditTextContent(arEtUsername), CygStringUtil.getEditTextContent(arEtPassword), image)) { CygToast.showToast("不能為空!!!"); return; } pd.setTitle("上傳圖片"); pd.setMessage("正在火速上傳,請稍後...."); pd.setCanceledOnTouchOutside(false); pd.show(); String url = "https://192.168.1.101:8080/MyWeb/UploadServlet"; RequestParams params = new RequestParams(); params.put("username", arEtUsername.getText().toString()); params.put("password", arEtPassword.getText().toString()); Log.d(TAG,"userhead=====" + image); params.put("userhead", image); RequestUtils.ClientPost(url, params, new NetCallBack() { @Override public void onMySuccess(byte[] response) { Log.d(TAG,"upload picture success---->" + new String(response)); Toast.makeText(this,"json=" + new String(response),Toast.LENGTH_SHORT).show(); pd.dismiss(); } @Override public void onMyFailure(byte[] response, Throwable throwable) { pd.dismiss(); Log.e(TAG,new String(response)+"\n"+ throwable.toString()); } }); } 

界面顯示注冊成功,接下來去服務器的文件夾下看看,圖片確實有了;再去數據庫查剛剛那條記錄——咦,怎麼是空的?仔細想想,服務器裡有圖片,數據庫卻沒數據,那肯定是存儲過程出了錯。看看服務端日誌,果然報錯:原來是上傳的圖片編碼太長,數據庫字段長度不夠。之前該字段是 varchar(45),改成 varchar(100) 再試一次,清空服務器舊圖片重新上傳,這回成功了!

好了,圖片上傳就到這裡,心動的同學趕緊動手試試吧!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved