首页 > 解决方案 > 是否可以使用 android 内容 uri 路径创建文件?

问题描述

我从手机图库中得到如下路径。

private fun fetchGalleryImages(context: Context, rowsPerLoad: Int): List<GalleryPicture> {
    val cursor = getGalleryCursor(context)

    if (cursor != null && !allLoaded) {
        val totalRows = cursor.count
        val galleryImageUrls = ArrayList<GalleryPicture>(totalRows)
        allLoaded = rowsToLoad == totalRows
        if (rowsToLoad < rowsPerLoad) {
            rowsToLoad = rowsPerLoad
        }

        for (i in startingRow until totalRows) {
            cursor.moveToPosition(i)
            val dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media._ID) //get column index
        
            val imageURI = ContentUris.withAppendedId(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                cursor.getLong(dataColumnIndex))

            val path = imageURI.toString()

            Log.d("ImagePath", "1) image path $path")

            galleryImageUrls.add(GalleryPicture(path)) //get Image path from column index
        }

        startingRow = rowsToLoad

        if (rowsPerLoad > totalRows || rowsToLoad >= totalRows)
            rowsToLoad = totalRows
        else {
            if (totalRows - rowsToLoad <= rowsPerLoad)
                rowsToLoad = totalRows
            else
                rowsToLoad += rowsPerLoad
        }

        cursor.close()
    
        return galleryImageUrls
    }

    return emptyList()
}

private fun getGalleryCursor(context: Context): Cursor? {
    val externalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val columns = arrayOf(MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DATE_MODIFIED)
    val orderBy = MediaStore.MediaColumns.DATE_MODIFIED //order data by modified
    return context.contentResolver
        .query(
            externalUri,
            columns,
            null,
            null,
            "$orderBy DESC"
        )//get all data in Cursor by sorting in DESC order
}

如果看上面的第一个日志,显示的是查找图片路径的日志,值如下:

内容://媒体/外部/图像/媒体/18503

如果我使用上面指定的路径插入图像Glide,照片将正常显示。

Glide.with(this).load(path).into(img)

问题是File无法使用该路径创建。

val file = File(path)
// always null...

目的是创建 aFile并将其导出为S3as MultipartBody.Part,如何创建文件?

标签: androidandroid-file

解决方案


推荐阅读