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

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

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

  1. @AndroidEntryPoint
  2. class MainActivity : ComponentActivity() {
  3. override fun onCreate(savedInstanceState: Bundle?) {
  4. super.onCreate(savedInstanceState)
  5. setContent {
  6. var selectedImageUri by remember { mutableStateOf<Uri?>(null) }
  7. val singlePhotoPikerLauncher = rememberLauncherForActivityResult(
  8. contract = ActivityResultContracts.PickVisualMedia(),
  9. onResult = { uri -> selectedImageUri = uri}
  10. )
  11. RandomAnimalClientTheme {
  12. // A surface container using the 'background' color from the theme
  13. Column (
  14. modifier = Modifier
  15. .fillMaxSize()
  16. .padding(32.dp)
  17. ){
  18. Spacer(modifier = Modifier.height(8.dp))
  19. Button(onClick = {
  20. singlePhotoPikerLauncher.launch(
  21. PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
  22. )
  23. Log.d("URI", selectedImageUri.toString())
  24. }) {
  25. Text(text="Create new animal")
  26. }
  27. AsyncImage(model = selectedImageUri, contentDescription = null )
  28. }
  29. }
  30. }
  31. }
  32. }

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

  1. val viewModel: MainViewModel = hiltViewModel()
  2. Button(onClick = {
  3. if(selectedImageUri!=null){
  4. val file = File(cacheDir, "myImage.jpg")
  5. file.createNewFile()
  6. file.outputStream().use{ assets.open("cat.jpg").copyTo(it) }
  7. viewModel.sendNewAnimal(
  8. animalName = "cat",
  9. animalDesc = "a cute mammal",
  10. animalImage = file
  11. )
  12. }
  13. }
  14. ) {
  15. Text(text="send new animal")
  16. }

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

  1. val file = File(selectedImageUri.path)

  1. val file = selectedImageUri.toFile()

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

xwbd5t1u

xwbd5t1u1#

尝试使用contentResolver.openInputStream(uri)

相关问题