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

Android 取得下載檔案的真實檔名

編輯:關於 Android 程式設計

在開發檔案下載功能時,我們常常需要從一個 URL 中解析出檔案的真實名稱。由於伺服器可能會透過 HTTP 標頭指定檔名,單純從 URL 擷取往往並不可靠。以下提供一個實用的方法來解決這個問題。

public static String getReallyFileName(String url) {
    String filename = "";
    URL myURL;
    HttpURLConnection conn = null;
    if (url == null || url.length() < 1) {
        return null;
    }
    try {
        myURL = new URL(url);
        conn = (HttpURLConnection) myURL.openConnection();
        conn.connect();
        conn.getResponseCode();
        URL absUrl = conn.getURL();  // 獲得真實 Url
        Log.e("H3c", "x:" + absUrl);

        // 可選擇列印伺服器 Header 資訊以利除錯
        // Map<String, List<String>> map = conn.getHeaderFields();
        // for (String str : map.keySet()) {
        //     if (str != null) {
        //         Log.e("H3c", str + map.get(str));
        //     }
        // }

        // 透過 Content-Disposition 取得檔名,這點與伺服器實作有關,需靈活應變
        filename = conn.getHeaderField("Content-Disposition");
        if (filename == null || filename.length() < 1) {
            filename = absUrl.getFile();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
            conn = null;
        }
    }
    return filename;
}

實作要點

這個方法的關鍵在於優先嘗試從 Content-Disposition 標頭中讀取檔名。當伺服器在回應標頭中提供了這個欄位時,我們就能取得最準確的檔名(通常還能避免中文亂碼或特殊字元的問題)。若該標頭不存在,則退而求其次,直接從重新導向後的真實 URL(conn.getURL())中擷取檔案路徑。

需要留意的是,Content-Disposition 的解析在實務上會因伺服器而異,有時其值可能包含額外的前綴(如 attachment; filename=),因此實際應用時可能需要進一步的字串處理,才能取出純粹的檔名。

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