1 打开文件管理器
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "*/*"//设置类型,我这里是任意类型,任意后缀的可以这样写。
intent.addCategory(Intent.CATEGORY_OPENABLE)
startActivityForResult(intent, 120)
2 文件选择回调
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 120 && resultCode == RESULT_OK) {
val uri = data?.data
if (Uri2PathUtil.getRealPathFromUri(this, uri) != null) {
//从uri得到绝对路径,并获取到file文件
val file = File(Uri2PathUtil.getRealPathFromUri(this, uri))
uploadFileViewModel.uploadHead(file)
} else {
LogUtils.e("获取文件失败")
}
}
}
3 工具类 uri转绝对路径
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import androidx.loader.content.CursorLoader;
public class Uri2PathUtil {
//复杂版处理 (适配多种API)
public static String getRealPathFromUri(Context context, Uri uri) {
int sdkVersion = Build.VERSION.SDK_I