Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

Android 上傳文件到服務器:HttpURLConnection 實現 multipart 上傳(從零開始學 Android)

編輯:Android 技術基礎

Android 上傳文件並沒有想像中神秘,本質上和 Java EE 裡的做法一致:把文件讀成字節流,按照 HTTP 協議約定拼裝成 multipart/form-data 的請求體,寫進輸出流,再從輸入流讀回服務器的響應。真正容易翻車的地方只有一處——Content-Type 與 boundary 的配置。這一步錯了,服務器永遠收不到文件,且不會給你任何有幫助的提示。

上傳的四個關鍵要素

把請求體拆開看,一次成功的上傳需要滿足:

  1. 請求方法為 POST,並同時開啟輸入流與輸出流;
  2. Content-Type 設為 multipart/form-data,並附上一個隨機生成的 boundary;
  3. 請求體按「--boundary → 頭部 → 空行 → 文件內容 → 換行」的格式組織,結尾用 --boundary-- 收束;
  4. name 屬性必須與服務器端約定的參數名一致,否則後台取不到文件。

上傳工具類

把上述流程封裝成一個靜態方法,入參只需文件和目標 URL:

public class UploadUtil {

    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 1000;   // 超時時間
    private static final String CHARSET = "utf-8";   // 字符編碼

    /**
     * 上傳文件到服務器
     * @param file        待上傳的文件
     * @param RequestURL  請求地址
     * @return            服務器返回的響應內容
     */
    public static String uploadFile(File file, String RequestURL) {
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString();  // 隨機邊界標識
        String PREFIX = "--";
        String LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data";

        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);      // 允許輸入流
            conn.setDoOutput(true);     // 允許輸出流
            conn.setUseCaches(false);   // 不使用緩存
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Charset", CHARSET);
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type",
                    CONTENT_TYPE + ";boundary=" + BOUNDARY);

            if (file != null) {
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                // 1. 拼接文件頭部
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                // name 為服務器端需要的 key;filename 需含擴展名,例如 abc.png
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""
                        + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream;charset="
                        + CHARSET + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());

                // 2. 寫入文件內容
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();

                // 3. 寫入結束標識
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();

                // 4. 讀取響應
                int res = conn.getResponseCode();
                Log.e(TAG, "response code:" + res);
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
                Log.e(TAG, "result : " + result);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

調用界面

界面很簡單:一個「選擇圖片」按鈕、一個「上傳圖片」按鈕,加一個 ImageView 用於預覽。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button
        android:id="@+id/selectImage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="選擇圖片" />

    <Button
        android:id="@+id/uploadImage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="上傳圖片" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Activity 中實現兩件事:通過系統 Intent 挑選圖片並取回真實路徑,以及把路徑交給工具類上傳。

case R.id.selectImage:
    // 調用系統內置 Intent 過濾圖片,也可以改成其他類型
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent, 1);
    break;

case R.id.uploadImage:
    File file = new File(picPath);
    if (file != null) {
        String request = UploadUtil.uploadFile(file, requestURL);
        uploadImage.setText(request);
    }
    break;

在 onActivityResult 中取出圖片的真實路徑,並順手做一次後綴名校驗:

Uri uri = data.getData();
String[] pojo = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, pojo, null, null, null);
if (cursor != null) {
    ContentResolver cr = getContentResolver();
    int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String path = cursor.getString(colunm_index);

    // 若使用第三方文件管理器,選中的不一定是圖片,需校驗後綴
    if (path.endsWith("jpg") || path.endsWith("png")) {
        picPath = path;
        Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
        imageView.setImageBitmap(bitmap);
    } else {
        alert();
    }
} else {
    alert();
}

非法文件用一個簡單的 AlertDialog 提示並把 picPath 置空即可。

幾個實踐中容易踩的坑

忘記加網絡權限。 上傳屬於網絡請求,AndroidManifest.xml 中必須聲明 android.permission.INTERNET,否則會直接拋出異常。

文件參數名撞關鍵字。 服務端若是 Java EE,name 使用了程式語言關鍵字或特殊字符,解析時容易出現各種難以定位的問題,盡量避開。

文件類型兩端不一致。 上傳時聲明的 Content-Type 必須和服務端期望的一致,否則上傳必然失敗。想上傳其他類型的文件,改動過濾條件和 MIME 類型即可。

主線程網絡請求。 較新版本的 Android 系統禁止在主線程執行網絡 I/O,實際項目中應把 UploadUtil.uploadFile 放進子線程或異步任務中調用,避免 NetworkOnMainThreadException。

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