kotlin 将从URI访问的图像发送到服务器

z9zf31ra  于 2023-10-23  发布在  Kotlin
关注(0)|答案(1)|浏览(101)

我能够从我的android库中检索URI的图像,然后使用coil库将其显示在AsyncImage中。

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            var selectedImageUri by remember { mutableStateOf<Uri?>(null) }

            val singlePhotoPikerLauncher = rememberLauncherForActivityResult(
                contract = ActivityResultContracts.PickVisualMedia(),
                onResult = { uri -> selectedImageUri = uri}
            )

            RandomAnimalClientTheme {
                // A surface container using the 'background' color from the theme
                Column (
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(32.dp)
                ){

                    Spacer(modifier = Modifier.height(8.dp))

                    Button(onClick = {
                        singlePhotoPikerLauncher.launch(
                            PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
                        )
                        Log.d("URI", selectedImageUri.toString())
                    }) {
                        Text(text="Create new animal")
                    }

                    AsyncImage(model = selectedImageUri, contentDescription = null )

                }
            }
        }
    }
}

我也可以像这样向服务器发送一个多部分请求:

val viewModel: MainViewModel = hiltViewModel()

Button(onClick = {
         if(selectedImageUri!=null){
             val file = File(cacheDir, "myImage.jpg")
             file.createNewFile()
             file.outputStream().use{ assets.open("cat.jpg").copyTo(it) }
             viewModel.sendNewAnimal(
                   animalName = "cat",
                   animalDesc = "a cute mammal",
                   animalImage = file
                   )
             }
       }
) {
        Text(text="send new animal")
}

问题是,我不知道如何从应用程序外部发送文件,例如从画廊。如前所述,我只能访问URI。
我已经尝试过像这样将URI转换为实际的File对象:

val file = File(selectedImageUri.path)

val file = selectedImageUri.toFile()

但我会出错。
我该怎么办?

xwbd5t1u

xwbd5t1u1#

尝试使用contentResolver.openInputStream(uri)

相关问题