擷取檔案資訊

在用戶端應用程式嘗試處理含有內容 URI 的檔案之前,應用程式可從伺服器應用程式要求檔案的相關資訊,包括檔案的資料類型和檔案大小。資料類型可協助用戶端應用程式判斷能否處理檔案,而檔案大小可協助用戶端應用程式設定檔案的緩衝處理和快取功能。

本課程示範如何查詢伺服器應用程式的 FileProvider,以擷取檔案的 MIME 類型和大小。

擷取檔案的 MIME 類型

檔案的資料類型會指示用戶端應用程式應如何處理檔案的內容。為了取得內容 URI 中共用檔案的資料類型,用戶端應用程式會呼叫 ContentResolver.getType()。這個方法會傳回檔案的 MIME 類型。根據預設,FileProvider 會根據副檔名決定檔案的 MIME 類型。

下列程式碼片段說明用戶端應用程式將內容 URI 傳回用戶端後,如何擷取檔案的 MIME 類型:

Kotlin

    ...
    /*
     * Get the file's content URI from the incoming Intent, then
     * get the file's MIME type
     */
    val mimeType: String? = returnIntent.data?.let { returnUri ->
        contentResolver.getType(returnUri)
    }
    ...

Java

    ...
    /*
     * Get the file's content URI from the incoming Intent, then
     * get the file's MIME type
     */
    Uri returnUri = returnIntent.getData();
    String mimeType = getContentResolver().getType(returnUri);
    ...

擷取檔案名稱和大小

FileProvider 類別提供 query() 方法的預設實作方式,會傳回 Cursor 中與內容 URI 相關聯的檔案名稱和大小。預設導入方式會傳回兩個資料欄:

DISPLAY_NAME
檔案名稱,顯示為 String。這個值與 File.getName() 傳回的值相同。
SIZE
檔案大小,以位元組為單位,long。這個值與 File.length() 傳回的值相同

用戶端應用程式可將 query() 的所有引數設為 null (內容 URI 除外),藉此取得檔案的 DISPLAY_NAMESIZE。舉例來說,下列程式碼片段會擷取檔案的 DISPLAY_NAMESIZE,並在獨立的 TextView 中分別顯示兩者:

Kotlin

    /*
     * Get the file's content URI from the incoming Intent,
     * then query the server app to get the file's display name
     * and size.
     */
    returnIntent.data?.let { returnUri ->
        contentResolver.query(returnUri, null, null, null, null)
    }?.use { cursor ->
        /*
         * Get the column indexes of the data in the Cursor,
         * move to the first row in the Cursor, get the data,
         * and display it.
         */
        val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
        val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
        cursor.moveToFirst()
        findViewById<TextView>(R.id.filename_text).text = cursor.getString(nameIndex)
        findViewById<TextView>(R.id.filesize_text).text = cursor.getLong(sizeIndex).toString()
        ...
    }

Java

    ...
    /*
     * Get the file's content URI from the incoming Intent,
     * then query the server app to get the file's display name
     * and size.
     */
    Uri returnUri = returnIntent.getData();
    Cursor returnCursor =
            getContentResolver().query(returnUri, null, null, null, null);
    /*
     * Get the column indexes of the data in the Cursor,
     * move to the first row in the Cursor, get the data,
     * and display it.
     */
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
    returnCursor.moveToFirst();
    TextView nameView = (TextView) findViewById(R.id.filename_text);
    TextView sizeView = (TextView) findViewById(R.id.filesize_text);
    nameView.setText(returnCursor.getString(nameIndex));
    sizeView.setText(Long.toString(returnCursor.getLong(sizeIndex)));
    ...

如需其他相關資訊,請參閱: