Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从android设备获取文件?_Android - Fatal编程技术网

如何从android设备获取文件?

如何从android设备获取文件?,android,Android,我有一个服务器,我应该在其中下载BASE64中的文件(不要问我为什么有这个)。现在我正在上传pdf文件。目前,我正在尝试从设备获取文件路径,然后将其解析为base64。它可以工作,但当我试图从非设备(例如谷歌照片)获取文件时,它不起作用。最好的方法是什么 @SuppressLint("NewApi") @Throws(URISyntaxException::class) fun getFilePath(context: Context, uri: Uri): String? { var

我有一个服务器,我应该在其中下载BASE64中的文件(不要问我为什么有这个)。现在我正在上传pdf文件。目前,我正在尝试从设备获取文件路径,然后将其解析为base64。它可以工作,但当我试图从非设备(例如谷歌照片)获取文件时,它不起作用。最好的方法是什么

@SuppressLint("NewApi")
@Throws(URISyntaxException::class)
fun getFilePath(context: Context, uri: Uri): String? {
    var uri = uri
    var selection: String? = null
    var selectionArgs: Array<String>? = null
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (Build.VERSION.SDK_INT < 28 && DocumentsContract.isDocumentUri(context.applicationContext, uri)) {
        if (isExternalStorageDocument(uri)) {
            val docId = DocumentsContract.getDocumentId(uri)
            val split =
                docId.split(":".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
            return Environment.getExternalStorageDirectory().path + "/" + split[1]
        } else if (isDownloadsDocument(uri)) {
            val id = DocumentsContract.getDocumentId(uri)
            uri = ContentUris.withAppendedId(
                Uri.parse("content://downloads/public_downloads"),
                java.lang.Long.valueOf(id)
            )
        } else if (isMediaDocument(uri)) {
            val docId = DocumentsContract.getDocumentId(uri)
            val split =
                docId.split(":".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
            val type = split[0]
            if ("image" == type) {
                uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            } else if ("video" == type) {
                uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            } else if ("audio" == type) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
            }
            selection = "_id=?"
            selectionArgs = arrayOf(split[1])
        } else if (isGooglePhotosUri(uri)) {

        }
    } else if (Build.VERSION.SDK_INT >= 28) {
        return uri.path.split(":")[1]
    }
    if ("content".equals(uri.getScheme(), ignoreCase = true)) {
        val projection = arrayOf<String>(MediaStore.Images.Media.DATA)
        var cursor: Cursor? = null
        try {
            cursor = context.contentResolver
                .query(uri, projection, selection, selectionArgs, null)
            val column_index = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            if (cursor!!.moveToFirst()) {
                return cursor!!.getString(column_index)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    } else if ("file".equals(uri.getScheme(), ignoreCase = true)) {
        return uri.getPath()
    }
    return null
}

fun isExternalStorageDocument(uri: Uri): Boolean {
    return "com.android.externalstorage.documents" == uri.getAuthority()
}

fun isDownloadsDocument(uri: Uri): Boolean {
    return "com.android.providers.downloads.documents" == uri.getAuthority()
}

fun isMediaDocument(uri: Uri): Boolean {
    return "com.android.providers.media.documents" == uri.getAuthority()
}

fun isGooglePhotosUri(uri: Uri): Boolean {
    return uri.authority.contains("com.google.android.apps")
}
@SuppressLint(“NewApi”)
@抛出(URISyntaxException::类)
有趣的getFilePath(context:context,uri:uri):字符串?{
var uri=uri
变量选择:字符串?=null
var selectionArgs:数组?=null
//Uri在KITKAT(Android 4.4)之后的版本中是不同的,我们需要
if(Build.VERSION.SDK_INT<28&&DocumentsContract.isDocumentUri(context.applicationContext,uri)){
if(isExternalStorageDocument(uri)){
val docId=DocumentsContract.getDocumentId(uri)
瓦尔斯普利特=
docId.split(“:”.toRegex()).droplastwile({it.isEmpty()}).toTypedArray()
返回Environment.getExternalStorageDirectory().path+“/”+split[1]
}else if(isDownloadsDocument(uri)){
val id=DocumentsContract.getDocumentId(uri)
uri=ContentUris.withAppendedId(
解析content://downloads/public_downloads"),
java.lang.Long.valueOf(id)
)
}else if(isMediaDocument(uri)){
val docId=DocumentsContract.getDocumentId(uri)
瓦尔斯普利特=
docId.split(“:”.toRegex()).droplastwile({it.isEmpty()}).toTypedArray()
val类型=拆分[0]
如果(“图像”==类型){
uri=MediaStore.Images.Media.EXTERNAL\u CONTENT\u uri
}else if(“视频”==类型){
uri=MediaStore.Video.Media.EXTERNAL\u CONTENT\u uri
}else if(“音频”==类型){
uri=MediaStore.Audio.Media.EXTERNAL\u CONTENT\u uri
}
selection=“\u id=?”
selectionArgs=arrayOf(拆分[1])
}else if(isGooglePhotosUri(uri)){
}
}else if(Build.VERSION.SDK_INT>=28){
返回uri.path.split(“:”[1]
}
if(“content”.equals(uri.getScheme(),ignoreCase=true)){
val projection=arrayOf(MediaStore.Images.Media.DATA)
变量游标:游标?=null
试一试{
cursor=context.contentResolver
.query(uri、投影、选择、selectionArgs、null)
val column\u index=cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
if(游标!!.moveToFirst()){
返回游标!!.getString(列索引)
}
}捕获(e:例外){
e、 printStackTrace()
}
}else if(“file”.equals(uri.getScheme(),ignoreCase=true)){
返回uri.getPath()
}
返回空
}
有趣的isExternalStorageDocument(uri:uri):布尔值{
返回“com.android.externalstorage.documents”==uri.getAuthority()
}
fun isDownloadsDocument(uri:uri):布尔值{
返回“com.android.providers.downloads.documents”==uri.getAuthority()
}
有趣的isMediaDocument(uri:uri):布尔值{
返回“com.android.providers.media.documents”==uri.getAuthority()
}
有趣的iGoogle照片uri(uri:uri):布尔值{
返回uri.authority.contains(“com.google.android.apps”)
}

您已经输入了
Uri
-使用它阅读内容-有关更多信息,请参阅
ContentResolver
官方文档谢谢。这有帮助。以及如何获取此文件的名称(我指的是真实名称,而不是“document/99”)?您无法获取
文件
-所有您可以获取的
输入流
用于内容读取欢迎您尝试
DocumentFile.fromSingleUri()
,然后对生成的
DocumentFile调用
getName()
。这可能有效,也可能无效,这取决于您如何获取
Uri