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

Android 原生實作檔案上傳到伺服器

編輯:關於 Android 程式設計

檔案上傳是 B/S 應用的基本功能,Android 端其實也能做到,而且不必引入任何第三方套件——用 HttpURLConnection 手工組出 multipart/form-data 請求即可。本文示範把本機的音訊檔 POST 到一個 JSP 接收端。

一、MainActivity 主體

 package com.xzq.upload; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity{ private String newName = "htys.mp3"; //要上傳的本地文件路徑 private String uploadFile = "/data/data/com.xzq/htys.mp3"; //上傳到服務器的指定位置 private String actionUrl = "https://192.168.100.100:8080/upload/upload.jsp"; private TextView mTextView1; private TextView mTextView2; private Button mButton1; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView1 = (TextView) findViewById(R.id.myText2); mTextView1.setText("FilePath:/n" + uploadFile); mTextView2 = (TextView) findViewById(R.id.myText3); mTextView2.setText("UploadPath:/n" + actionUrl); /* 設定mButton的onClick事件處理 */ mButton1 = (Button) findViewById(R.id.myButton); mButton1.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ uploadFile(); } }); } private void uploadFile(){ String end = "/r/n"; String Hyphens = "--"; String boundary = "*****"; try{ URL url = new URL(actionUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); /* 允許Input、Output,不使用Cache */ con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); /* 設定傳送的method=POST */ con.setRequestMethod("POST"); /* setRequestProperty */ con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); /* 設定DataOutputStream */ DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(Hyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=/"file1/";filename=/"" + newName + "/"" + end); ds.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream = new FileInputStream(uploadFile); /* 設定每次寫入1024bytes */ int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; /* 從文件讀取數據到緩沖區 */ while ((length = fStream.read(buffer)) != -1){ /* 將數據寫入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(Hyphens + boundary + Hyphens + end); fStream.close(); ds.flush(); /* 取得Response內容 */ InputStream is = con.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1){ b.append((char) ch); } System.out.println("上傳成功"); Toast.makeText(MainActivity.this, "上傳成功", Toast.LENGTH_LONG) .show(); ds.close(); } catch (Exception e){ System.out.println("上傳失敗" + e.getMessage()); Toast.makeText(MainActivity.this, "上傳失敗" + e.getMessage(), Toast.LENGTH_LONG).show(); } } } 

二、關鍵步驟拆解

1. 準備連線。開啟 Input/Output、關閉快取,並指定 POST 方法。

2. 宣告 boundary。這是一串不會出現在檔案內容中的分隔字串,伺服器靠它切分各個表單欄位。這裡用 ***** 只是示意,實務上建議用隨機亂數產生以降低碰撞機率。

3. 寫入檔頭。先送 --boundary,接著一行 Content-Disposition: form-data; name="file1"; filename="htys.mp3",然後空一行,才開始是檔案內容。這個格式錯一個換行,伺服器就會解析失敗。

4. 串流搬資料。用 1024 bytes 的緩衝區反覆讀寫,避免一次把整個檔案載入記憶體造成 OOM。

5. 收尾。寫入結尾換行與 --boundary--,flush 後讀取回應。

三、別忘了權限

在 AndroidManifest.xml 中加入網路權限:

 <uses-permission android:name="android.permission.INTERNET" />

四、實務上的幾點提醒

這個範例求的是「看得懂原理」,若要上 production,建議補強以下幾處:

  • 執行緒:網路請求絕對不能跑在主執行緒,Android 4.0 之後會直接拋 NetworkOnMainThreadException,請改用背景執行緒或 coroutine。
  • 進度回報:上傳大檔時使用者需要知道進度,可在寫入迴圈中累加已送位元組數並回呼。
  • 錯誤處理:範例用 catch (Exception) 一網打盡,正式環境應區分 FileNotFoundException(本機檔案不存在)與 IOException(網路異常),並記得在 finally 中關閉串流。
  • 檔名編碼:中文檔名建議做 URL Encode,否則接收端容易拿到亂碼。
  • HTTPS:明文 HTTP 傳輸檔案等同裸奔,正式環境務必改用 TLS。

以上就是以原生 API 實作 Android 檔案上傳的完整流程,理解這套 multipart 協議之後,再換成 OkHttp 或 Retrofit 也會清楚它們背後到底做了什麼。

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