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

Android 使用 Base64 上傳圖片到伺服器的完整流程

編輯:關於 Android 程式設計

早期上傳圖片多採用 HttpServlet 的方式,實際用過 Base64 之後會發現它比傳統串流上傳方便不少,這裡就把整個流程記錄下來,供大家參考嘗試。

一、前台:把圖片轉成 Base64 字串

直接把 Bitmap 壓縮並編碼即可:

/**
 * 將 Bitmap 轉換成 Base64 字串
 * @param bit 傳入的 Bitmap 物件
 * @return Base64 字串
 */
public String Bitmap2StrByBase64(Bitmap bit){
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bit.compress(CompressFormat.JPEG, 40, bos);// 第二個參數為壓縮品質
    byte[] bytes = bos.toByteArray();
    return Base64.encodeToString(bytes, Base64.DEFAULT);
}

二、前台:發送資料

呼叫 setImgByStr() 方法,第一個參數 imgStr 為 Bitmap 轉出的 Base64 字串,第二個參數 imgName 為含副檔名的圖片名稱(例如 photo.jpg):

public static String host = "https://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 + "\n");
        }
        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 (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            response = client.execute(httpPost);
        } catch (Exception 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 (Exception 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);
}

四、後台:解碼並還原圖片

/**
 * 以 Base64 解碼並生成圖片
 * @param imgStr 解碼後的字串
 */
public boolean string2Image(String imgStr, String imgFilePath) {
    // 對位元組陣列字串進行 Base64 解碼並生成圖片
    if (imgStr == null) return false;
    try {
        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;
    }
}

這樣就完成了!上傳成功時前端會收到 true,失敗則收到 false。整體來說,Base64 的做法省去處理 multipart 的麻煩,特別適合小圖上傳的場景,不過大圖仍需留意字串過長帶來的效能與記憶體問題。

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