很多初學者以為上傳圖片是傳「本地路徑」,實則完全錯誤。本文徹底講清Android圖片上傳的核心機制與標準實現。
// 1. 選圖
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE);
// 2. onActivityResult獲取Uri
Uri selectedImage = data.getData();
// 3. 上傳
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), getFileFromUri(uri));
MultipartBody.Part part = MultipartBody.Part.createFormData("file", getFileName(uri), requestFile);
RequestBody desc = RequestBody.create(MediaType.parse("text/plain"), "avatar");
apiService.uploadAvatar(part, desc).enqueue(new Callback() {
@Override public void onResponse(Call call, Response response) { /* 成功 */ }
@Override public void onFailure(Call call, Throwable t) { /* 失敗 */ }
});
// 輔助:Uri轉File(僅用於獲取文件名/大小,實際上傳用流)
private File getFileFromUri(Uri uri) { /* 使用ContentResolver查詢_DISPLAY_NAME,_SIZE,開輸入流寫入臨時文件或直接用流 */ }
記住:客戶端只有輸出流,服務器只有輸入流,中間靠HTTP協議傳輸二進制數據。