6

I have a form where I need to attach a file from the phone. I have been looking for a file picker but it can only access images, not files like pdf, doc, docx, etc.
How to achieve this all in jetpack compose?

hippietrail
  • 15,848
  • 18
  • 99
  • 158

1 Answers1

9

According to documentation, it could be done with Intent.ACTION_OPEN_DOCUMENT.

In Compose it you need rememberLauncherForActivityResult to do it:

var pickedImageUri by remember { mutableStateOf<Uri?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
    println("selected file URI ${it.data?.data}")
    pickedImageUri = it.data?.data
}
pickedImageUri?.let {
    Text(it.toString())
}
Button(
    onClick = {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            .apply {
                addCategory(Intent.CATEGORY_OPENABLE)
            }
        launcher.launch(intent)
    }
) {
    Text("Select")
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220