在android項目中,很多情況下上傳頭像的需求,像qq,新浪微博,微信,飛信等很多應用都有這樣的功能。
之前我寫過的兩篇文章:andorid下從相冊選取/拍照選取一張相片並剪切和android下Bitmap和base64之間的轉換把他們綜合起來,就可以來實現頭像從相冊/拍照選取,後裁剪再上傳的功能
完整源碼下載
這裡我隻貼出上傳圖片的方法代碼,至於怎麼獲取到獲取到圖片,請看andorid下從相冊選取/拍照選取一張相片並剪切
/* * 上傳圖片 */ public void upload(View view) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); byte[] buffer = out.toByteArray(); byte[] encode = Base64.encode(buffer, Base64.DEFAULT); String photo = new String(encode); RequestParams params = new RequestParams(); params.put("photo", photo); String url = "https://110.65.99.66:8080/jerry/UploadImgServlet"; AsyncHttpClient client = new AsyncHttpClient(); client.post(url, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { if (statusCode == 200) { Toast.makeText(MainActivity.this, "頭像上傳成功!", 0) .show(); } else { Toast.makeText(MainActivity.this, "網絡訪問異常,錯誤碼:" + statusCode, 0).show(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Toast.makeText(MainActivity.this, "網絡訪問異常,錯誤碼 > " + statusCode, 0).show(); } }); } catch (Exception e) { e.printStackTrace(); } }
從上邊代碼可以看出,又用到我鐘愛的android-async-http 安卓異步http框架來訪問網絡
這樣一操作,圖片就會按Base64編碼格式傳送到服務器,而服務器端的代碼也是非常簡單的
package com.jerry.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; import com.sun.org.apache.xml.internal.security.utils.Base64; public class UploadImgServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); String photo = request.getParameter("photo"); try { // 對base64數據進行解碼 byte[] decode = Base64.decode(photo); File file = new File("e:\\decode.jpg"); if(!file.exists()) { file.createNewFile(); } FileOutputStream out = new FileOutputStream(file); out.write(decode); out.flush(); out.close(); } catch (Base64DecodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
這樣圖片就成功的保存帶E盤下