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

Android 上傳檔案到伺服器的完整實作

編輯:關於 Android 程式設計

檔案上傳是許多應用的必備功能。以下這份 UploadUtil 已將註解寫得相當清楚,透過 HttpURLConnection 以 multipart/form-data 方式 POST 上傳,隨取即用,方便隨時參考。

public class UploadUtil {

    private static final String TAG = "TTTTTT upload";
    private static final int TIME_OUT = 10 * 1000; // 超時時間
    private static final String CHARSET = "utf-8"; // 設定編碼

    public static String uploadFile(File file, String RequestURL) {
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString(); // 邊界標識,隨機生成
        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());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.flush();

                // 取得回應碼,200 代表成功
                int res = conn.getResponseCode();
                Log.e(TAG, "response code:" + res);
                if (res == 200) {
                    Log.e(TAG, "request success");
                    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);
                }
            } else {
                Log.e(TAG, "file not found!");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

整段邏輯先設定連線參數與邊界標識,接著以串流方式讀取檔案內容寫入輸出流,最後依據回應碼判斷上傳是否成功並解析伺服器回傳的結果。

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