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

Android 以 HTTP 協議實作檔案上傳

編輯:關於 Android 程式設計

檔案上傳是 App 的常見需求。實務上依檔案大小會有不同的最佳解法:小的走 HTTP multipart/form-data,大的則要考慮分塊上傳或 PUT 到物件儲存服務。本文示範前者——上傳一個小型 MP3。

先講適用範圍:HTTP 上傳適合比較小的檔案,一般建議在 2MB 以內。更大的檔案請改用分塊續傳或 HTTP PUT,否則記憶體與超時都會成問題。

1. MainActivity:收集表單並送出

 public class MainActivity extends Activity {

  private static final String TAG = "MainActivity";
  private EditText timelengthText;
  private EditText titleText;
  private EditText videoText;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button button = (Button) this.findViewById(R.id.button);
    timelengthText = (EditText) this.findViewById(R.id.timelength);
    videoText = (EditText) this.findViewById(R.id.video);
    titleText = (EditText) this.findViewById(R.id.title);

    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String title = titleText.getText().toString();
        String timelength = timelengthText.getText().toString();

        Map<String, String> params = new HashMap<String, String>();
        params.put("method", "save");
        params.put("title", title);
        params.put("timelength", timelength);

        try {
          // 取得 SD 卡目錄下的目標檔
          File uploadFile = new File(
              Environment.getExternalStorageDirectory(),
              videoText.getText().toString());

          // 封裝成 FormFile:檔名、檔案物件、表單欄位名、Content-Type
          FormFile formfile = new FormFile("02.mp3", uploadFile, "video", "audio/mpeg");

          SocketHttpRequester.post(
              "https://192.168.1.100:8080/videoweb/video/manage.do",
              params, formfile);

          Toast.makeText(MainActivity.this, R.string.success, 1).show();
        } catch (Exception e) {
          Toast.makeText(MainActivity.this, R.string.error, 1).show();
          Log.e(TAG, e.toString());
        }
      }
    });
  }
} 

這裡有兩個必須修正的問題:一是網路請求寫在主執行緒,Android 4.0 之後會直接拋出 NetworkOnMainThreadException,必須放到背景執行緒;二是讀取外部儲存空間需要 READ_EXTERNAL_STORAGE 權限(Android 6.0 以上還要執行期申請)。下面的工具類程式碼是原始寫法,正式使用前請先補上執行緒與權限處理。

2. 上傳工具類

這個類別提供四種能力:以 Socket 手寫 multipart 上傳、以 HttpURLConnection 送表單、以 HttpClient 送表單,以及上傳 XML。

 public class SocketHttpRequester {

  /** 發送 xml 資料 */
  public static byte[] postXml(String path, String xml, String encoding) throws Exception {
    byte[] data = xml.getBytes(encoding);
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
    conn.setRequestProperty("Content-Length", String.valueOf(data.length));
    conn.setConnectTimeout(5 * 1000);

    OutputStream outStream = conn.getOutputStream();
    outStream.write(data);
    outStream.flush();
    outStream.close();

    if (conn.getResponseCode() == 200) {
      return readStream(conn.getInputStream());
    }
    return null;
  }

  /**
   * 直接以 HTTP 協議提交資料,等同以下表單的功能:
   *
   * <FORM METHOD=POST ACTION="https://192.168.0.200:8080/ssi/fileload/test.do"
   *       enctype="multipart/form-data">
   *   <INPUT TYPE="text" NAME="name">
   *   <INPUT TYPE="text" NAME="id">
   *   <input type="file" name="imagefile"/>
   *   <input type="file" name="zip"/>
   * </FORM>
   *
   * @param path   上傳路徑(請避免使用 localhost 或 127.0.0.1 測試,
   *               因為它會指向模擬器本身,可改用區網 IP 或
   *               https://192.168.1.10:8080 這樣的路徑)
   * @param params 請求參數,key 為參數名、value 為參數值
   * @param files  上傳檔案
   */
  public static boolean post(String path, Map<String, String> params, FormFile[] files)
      throws Exception {

    final String BOUNDARY = "---------------------------7da2137580612";
    final String endline = "--" + BOUNDARY + "--\r\n";

    // 先算出檔案區的總長度(含分隔線與標頭)
    int fileDataLength = 0;
    for (FormFile uploadFile : files) {
      StringBuilder fileExplain = new StringBuilder();
      fileExplain.append("--").append(BOUNDARY).append("\r\n");
      fileExplain.append("Content-Disposition: form-data;name=\"")
                  .append(uploadFile.getParameterName())
                  .append("\";filename=\"").append(uploadFile.getFilname())
                  .append("\"\r\n");
      fileExplain.append("Content-Type: ").append(uploadFile.getContentType()).append("\r\n\r\n");
      fileExplain.append("\r\n");

      fileDataLength += fileExplain.length();
      if (uploadFile.getInStream() != null) {
        fileDataLength += uploadFile.getFile().length();
      } else {
        fileDataLength += uploadFile.getData().length;
      }
    }

    // 再算出文字參數區的內容
    StringBuilder textEntity = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
      textEntity.append("--").append(BOUNDARY).append("\r\n");
      textEntity.append("Content-Disposition: form-data; name=\"")
                .append(entry.getKey()).append("\"\r\n\r\n");
      textEntity.append(entry.getValue()).append("\r\n");
    }

    // 總長度 = 文字區 + 檔案區 + 結束標記
    int dataLength = textEntity.toString().getBytes().length
                   + fileDataLength
                   + endline.getBytes().length;

    URL url = new URL(path);
    int port = url.getPort() == -1 ? 80 : url.getPort();
    Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
    OutputStream outStream = socket.getOutputStream();

    // 依序送出 HTTP 請求標頭
    outStream.write(("POST " + url.getPath() + " HTTP/1.1\r\n").getBytes());
    outStream.write(("Accept: image/gif, image/jpeg, application/msword, */*\r\n").getBytes());
    outStream.write("Accept-Language: zh-CN\r\n".getBytes());
    outStream.write(("Content-Type: multipart/form-data; boundary=" + BOUNDARY + "\r\n").getBytes());
    outStream.write(("Content-Length: " + dataLength + "\r\n").getBytes());
    outStream.write("Connection: Keep-Alive\r\n".getBytes());
    outStream.write(("Host: " + url.getHost() + ":" + port + "\r\n").getBytes());

    // 標頭結束後要再送一個空行
    outStream.write("\r\n".getBytes());

    // 送出文字參數
    outStream.write(textEntity.toString().getBytes());

    // 送出各檔案
    for (FormFile uploadFile : files) {
      StringBuilder fileEntity = new StringBuilder();
      fileEntity.append("--").append(BOUNDARY).append("\r\n");
      fileEntity.append("Content-Disposition: form-data;name=\"")
                .append(uploadFile.getParameterName())
                .append("\";filename=\"").append(uploadFile.getFilname())
                .append("\"\r\n");
      fileEntity.append("Content-Type: ").append(uploadFile.getContentType()).append("\r\n\r\n");
      outStream.write(fileEntity.toString().getBytes());

      if (uploadFile.getInStream() != null) {
        // 邊讀邊寫,避免一次載入整個檔案
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = uploadFile.getInStream().read(buffer, 0, 1024)) != -1) {
          outStream.write(buffer, 0, len);
        }
        uploadFile.getInStream().close();
      } else {
        outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
      }
      outStream.write("\r\n".getBytes());
    }

    // 送出結束標記
    outStream.write(endline.getBytes());

    // 讀取回應,檢查狀態碼是否為 200
    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    if (reader.readLine().indexOf("200") == -1) {
      return false;
    }

    outStream.flush();
    outStream.close();
    reader.close();
    socket.close();
    return true;
  }

  /** 單檔上傳的多載版本 */
  public static boolean post(String path, Map<String, String> params, FormFile file)
      throws Exception {
    return post(path, params, new FormFile[]{file});
  }

  /** 以 DefaultHttpClient 提交表單 */
  public static byte[] postFromHttpClient(String path, Map<String, String> params, String encode)
      throws Exception {
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : params.entrySet()) {
      formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encode);
    HttpPost httppost = new HttpPost(path);
    httppost.setEntity(entity);

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httppost);
    return readStream(response.getEntity().getContent());
  }

  /** 以 HttpURLConnection 提交一般表單 */
  public static byte[] post(String path, Map<String, String> params, String encode)
      throws Exception {

    StringBuilder parambuilder = new StringBuilder();
    if (params != null && !params.isEmpty()) {
      for (Map.Entry<String, String> entry : params.entrySet()) {
        parambuilder.append(entry.getKey())
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue(), encode))
                    .append("&");
      }
      parambuilder.deleteCharAt(parambuilder.length() - 1);
    }

    byte[] data = parambuilder.toString().getBytes();
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(5 * 1000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Accept-Language", "zh-CN");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(data.length));
    conn.setRequestProperty("Connection", "Keep-Alive");

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(data);
    outStream.flush();
    outStream.close();

    if (conn.getResponseCode() == 200) {
      return readStream(conn.getInputStream());
    }
    return null;
  }

  /** 讀取輸入流為位元組陣列 */
  public static byte[] readStream(InputStream inStream) throws Exception {
    ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = -1;
    while ((len = inStream.read(buffer)) != -1) {
      outSteam.write(buffer, 0, len);
    }
    outSteam.close();
    inStream.close();
    return outSteam.toByteArray();
  }
} 

3. StreamTool:讀流的輔助類別

 public class StreamTool {
  /** 從輸入流讀取資料 */
  public static byte[] readInputStream(InputStream inStream) throws Exception {
    ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = inStream.read(buffer)) != -1) {
      outSteam.write(buffer, 0, len);
    }
    outSteam.close();
    inStream.close();
    return outSteam.toByteArray();
  }
} 

4. FormFile:封裝上傳檔案

用 JavaBean 把「檔名、表單欄位名、Content-Type、內容」打包起來。它支援兩種來源:小型檔案直接讀進記憶體,大型檔案則保留 InputStream 邊讀邊送。

 /**
 * 使用 JavaBean 封裝上傳檔案資料
 */
public class FormFile {

  private byte[] data;              // 上傳檔案的資料
  private InputStream inStream;     // 或串流形式
  private File file;
  private String filname;           // 檔案名稱
  private String parameterName;     // 表單欄位名稱
  private String contentType = "application/octet-stream";  // 內容類型

  /** 上傳小檔案:先把資料讀進記憶體 */
  public FormFile(String filname, byte[] data, String parameterName, String contentType) {
    this.data = data;
    this.filname = filname;
    this.parameterName = parameterName;
    if (contentType != null) this.contentType = contentType;
  }

  /** 上傳大檔案:一邊讀檔一邊上傳 */
  public FormFile(String filname, File file, String parameterName, String contentType) {
    this.filname = filname;
    this.parameterName = parameterName;
    this.file = file;
    try {
      this.inStream = new FileInputStream(file);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    if (contentType != null) this.contentType = contentType;
  }

  public File getFile() { return file; }
  public InputStream getInStream() { return inStream; }
  public byte[] getData() { return data; }
  public String getFilname() { return filname; }
  public void setFilname(String filname) { this.filname = filname; }
  public String getParameterName() { return parameterName; }
  public void setParameterName(String parameterName) { this.parameterName = parameterName; }
  public String getContentType() { return contentType; }
  public void setContentType(String contentType) { this.contentType = contentType; }
} 

multipart/form-data 的原理

整份程式碼最需要理解的,是這個格式本身。它的結構是:

--BOUNDARY\r\n
Content-Disposition: form-data; name="欄位名"\r\n
[Content-Type: ...]\r\n
\r\n
內容資料\r\n
--BOUNDARY\r\n
... 更多欄位 ...
--BOUNDARY--\r\n

所以 Content-Length 不能只算檔案大小,必須把每一段的分隔線、標頭、換行全部加進去——這正是 post() 方法開頭那兩個迴圈在做的事。算錯了伺服器會一直等不到結尾而逾時,這也是手寫上傳最常遇到的錯誤。

為什麼不建議這樣寫

這份程式碼的教學價值在於「讓你看清 HTTP 上傳到底長什麼樣」,但正式專案不該手寫 Socket。原因有三:

  • 邊界固定寫死。BOUNDARY 依 RFC 必須是隨機且不出現在內容中的字串,寫死有碰撞風險。
  • 錯誤處理幾乎沒有。網路中斷、伺服器回 4xx/5xx、逾時等情況都沒有妥善處理。
  • 已廢棄的 API。DefaultHttpClient 在 Android 6.0 中被移除,HttpURLConnection 才是官方推薦的低層 API。

現代的建議做法:

  • OkHttp:目前的事實標準,multipart 支援完善,連線池與攔截器機制也很好用。
  • Retrofit:搭配 OkHttp,用介面定義上傳端點,程式碼量最少。
  • WorkManager:上傳這種應該在背景持續進行的工作,交給它管理重試與約束條件(例如只在 Wi-Fi 下上傳)。

另外,若檔案較大或需要續傳,直接考慮與雲端儲存服務簽 URL、由客戶端用 HTTP PUT 上傳,會比經過自己的伺服器中轉省下大量頻寬成本。

總結:理解 multipart 的組成,但用成熟函式庫去實作它。這樣你既知道出問題時該看哪裡,也不必自己處理那些容易出錯的邊界條件。

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