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

Android 檔案上傳實作:從用戶端到 Servlet 伺服器的完整流程

編輯:關於 Android 程式設計

本文以一個最小可運行的範例,說明如何用 HttpURLConnection 把本機檔案以 multipart 方式上傳,並在伺服器端用 Servlet 接收寫入磁碟,同時透過自訂的串流類別回報上傳進度。

先看一下專案結構:

一、用戶端:MainActivity

關鍵點有三個:把耗時的網路寫入放到子執行緒、用 ProgressDialog 顯示進度、用 Handler 把進度從工作執行緒送回 UI 執行緒。

public class MainActivity extends Activity implements OnUploadListener {

    // 伺服器位址,實際使用時換成自己的
    private String urlString = "https://192.168.1.2:8080/UploadTest/Upload";

    String filePath;   // 要上傳的檔案完整路徑
    String fileName;   // 檔名
    ProgressDialog dialog;

    /** 讀取串流時同一個進度會被回呼很多次,靠這個變數去重,避免洗版 UI */
    int oldProcess;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.setProgress(msg.arg1);
            if (!dialog.isShowing()) {
                dialog.show();
            } else if (msg.arg1 == 100) {
                dialog.dismiss();
                toast("上傳完成!");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initProgressDialog();
    }

    public void upLoad(View v) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            filePath = sdcardPath + "/Abook/";
            File file = new File(filePath);
            // 這裡示範挑 Abook 資料夾裡的某個檔案,實務上要依需求決定
            fileName = file.list()[4];
            filePath += fileName;
        } else {
            toast("沒有記憶卡");
            return;
        }

        new Thread() {
            public void run() {
                try {
                    HttpUtil.sendFile(urlString, filePath, fileName, MainActivity.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /** 檔案讀取進度的回呼,process 介於 0~1 */
    @Override
    public void onUpload(double process) {
        int currentProcess = (int) (process * 100);
        if (currentProcess > oldProcess) {   // 只有真正前進才發訊息
            Message msg = handler.obtainMessage();
            msg.arg1 = currentProcess;
            handler.sendMessage(msg);
        }
        oldProcess = currentProcess;
    }

    private void initProgressDialog() {
        dialog = new ProgressDialog(this);
        dialog.setMax(100);
        dialog.setProgress(0);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setTitle("正在努力上傳...");
    }

    private void toast(String text) {
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    }
}

二、HttpUtil:組裝 multipart 請求

multipart 的格式其實很樸素:一組分隔符號(boundary)+ 每個區塊的描述標頭 + 內容。伺服器就是靠 boundary 切分資料。

public static String sendFile(String urlPath, String filePath, String newName,
                              OnUploadListener listener) throws Exception {
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "******";

    HttpURLConnection con = (HttpURLConnection) new URL(urlPath).openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestMethod("POST");
    con.setRequestProperty("Connection", "Keep-Alive");
    con.setRequestProperty("Charset", "UTF-8");
    con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    DataOutputStream ds = new DataOutputStream(con.getOutputStream());
    ds.writeBytes(twoHyphens + boundary + end);
    // 檔案區塊的描述:表單欄位名、檔名
    ds.writeBytes("Content-Disposition: form-data; "
            + "name=\"file1\";filename=\"" + newName + "\"" + end);
    ds.writeBytes(end);

    // 自訂的 FileInputStream,用來回報進度
    CustomFileInputStream fStream = new CustomFileInputStream(filePath);
    fStream.setOnUploadListener(listener);

    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    int length = -1;
    while ((length = fStream.read(buffer)) != -1) {
        ds.write(buffer, 0, length);
    }

    ds.writeBytes(end);
    ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
    fStream.close();
    ds.flush();

    // 讀取伺服器回應
    InputStream is = con.getInputStream();
    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = is.read()) != -1) {
        b.append((char) ch);
    }
    ds.close();
    return b.toString();
}

三、CustomFileInputStream:攔截 read 來算進度

進度=已讀位元組 ÷ 檔案總大小。總大小可以透過覆寫 available() 取得。

public class CustomFileInputStream extends FileInputStream {

    private OnUploadListener listener;
    private int total, done;
    private double process;

    public CustomFileInputStream(String path) throws FileNotFoundException {
        super(path);
        available();
    }

    @Override
    public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
        int result = super.read(buffer, byteOffset, byteCount);
        if (result > 0) {
            done += result;
            process = 1.0 * done / total;
            if (listener != null) {
                listener.onUpload(process);
            }
        }
        return result;
    }

    public void setOnUploadListener(OnUploadListener listener) {
        this.listener = listener;
    }

    @Override
    public int available() {
        try {
            total = super.available();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return total;
    }
}

public interface OnUploadListener {
    void onUpload(double process);
}

四、伺服器端:用 Servlet 收檔案

@WebServlet("/Upload")
public class Upload extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private final String savaPath = "E:\\uploads";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            return;
        }

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            // 迴圈可同時接收多個檔案
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    // 一般文字欄位
                    System.out.println(item.getFieldName() + ":" + item.getString());
                } else {
                    // 檔案欄位
                    String fileName = item.getName();
                    byte[] data = item.get();

                    File dir = new File(savaPath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File target = new File(savaPath, fileName);
                    if (target.exists()) {
                        target.delete();
                    }
                    FileOutputStream fos = new FileOutputStream(target);
                    fos.write(data);
                    fos.close();
                }
            }
            response.getWriter().write("UPLOAD_SUCCESS");
        } catch (FileUploadException e) {
            e.printStackTrace();
            response.getWriter().write("UPLOAD_FAILED");
        }
    }
}

伺服器端需要兩個 jar:commons-fileupload-1.3.1.jar 與 commons-io-2.4.jar。

五、實務上的注意事項

範例為了聚焦在主流程,省略了幾個實作上必須補齊的環節:上傳前應檢查檔案大小並在伺服器端做型別白名單;檔名不可直接信任,建議重新產生 UUID 或至少過濾路徑字元,避免路徑穿越;正式環境請改用 HTTPS,否則檔案內容在網路上等於裸奔。

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