編輯:關於 Android 程式設計
撰寫 WebService 介面時,字型和數值型資料都好處理,一旦碰上圖片就有點麻煩。最省事的做法是把檔案讀成位元組流,用 Base64 編碼成字串再送出去,服務端收到字串後解碼還原成檔案。這樣的好處是全程只走文字協定,不必額外處理 multipart;代價則是資料量增加約三分之一,因此並不適合大檔或大量批次上傳。
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 更省頻寬。
android-async-http 解析服務端 JSON:JavaEE 後端到 Android 客戶端全鏈路
本文走一條完整鏈路:JavaEE 服務端把數據庫內容封裝成 JSON 輸出,Android 客戶端用 android-async-http 異步拉取並渲染到 ListVi
Android 進程通信:用 AIDL 實現跨進程並發調用
AIDL 概述 用 Messenger 實現的 IPC 有一個明顯不足:Service 內部維護著一個 Messenger,Messenger 內部又維護著一個 Hand
Android 手勢交互實踐:MotionEvent、GestureDetector 與各手勢動作辨析
網上關於 Android 手勢的文章不算多,質量參差不齊,官方文檔在這塊也寫得相當含糊——不少常量和方法連一行說明都沒有。我把實際反覆嘗試的結果整理如下,供參考指正。
用 ViewPager 實現 Android 應用引導頁效果
許多 App 在首次安裝打開時,都會有一組功能介紹的引導頁——就像剛裝完微信時那樣,一張張圖片滑過,底部還有一排小圓點提示目前位置。本文示範如何用 ViewPager 實