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

Android 與 WebService 之間傳輸圖片:Base64 編碼方案實作

編輯:關於 Android 程式設計

撰寫 WebService 介面時,字型和數值型資料都好處理,一旦碰上圖片就有點麻煩。最省事的做法是把檔案讀成位元組流,用 Base64 編碼成字串再送出去,服務端收到字串後解碼還原成檔案。這樣的好處是全程只走文字協定,不必額外處理 multipart;代價則是資料量增加約三分之一,因此並不適合大檔或大量批次上傳。

客戶端:把圖片轉成 Base64 字串

public static void main(String[] args) throws IOException {
    File file = new File("d:/272.jpg");
    FileInputStream fis = new FileInputStream(file);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[1024];
    int count;
    while ((count = fis.read(buffer)) >= 0) {
        baos.write(buffer, 0, count);
    }

    // 進行 Base64 編碼
    String uploadBuffer = new String(Base64.encode(baos.toByteArray()));
    fis.close();

    writeSmilFile(uploadBuffer);
    System.out.println("uploadBuffer:" + uploadBuffer);
}

// 寫到 txt,方便先人工檢查編碼結果
public static void writeSmilFile(String content) {
    File file1 = new File("d:/123.txt");
    try {
        file1.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        OutputStreamWriter os =
                new OutputStreamWriter(new FileOutputStream(file1), "UTF-8");
        os.write(content);
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

服務端:解碼並落地存檔

/**
 * 接收 Android 端上傳的圖片並存檔
 * 客戶端的處理是:檔案 → 位元組流 → Base64 編碼字串
 */
public String getPhotoByAndroid(String photoPath) {
    // 正式環境請替換成實際的存放路徑
    String newFilePath = "D:/";
    String newFileName = UUID.randomUUID().toString() + ".jpg";
    FileOutputStream fos = null;
    try {
        byte[] buffer = new BASE64Decoder().decodeBuffer(photoPath);

        File destDir = new File(newFilePath);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        fos = new FileOutputStream(new File(destDir, newFileName));
        fos.write(buffer);   // 存檔
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("上傳圖片成功!" + newFilePath + newFileName);
    return newFileName;
}

幾個實務上的提醒

檔名務必用 UUID 這類方式重新產生,不要沿用客戶端傳來的名稱,一方面是避免中文或特殊字元造成的編碼問題,另一方面也能防止路徑穿越攻擊。解碼時建議對字串長度做上限檢查,並把寫檔操作放在 try-with-resources 中確保串流一定關閉。若圖片較大或需要一次上傳多張,改用 multipart/form-data 會比 Base64 更省頻寬。

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