检索文件信息

在客户端应用尝试处理具有其内容 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() 的所有参数(内容 URI 除外)设置为 null 来获取文件的 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)));
    ...

要了解更多相关信息,请参阅: