问题描述
我已经能够从图库中获取图片的 content:// Uri。我必须显示图像的预览并将其上传到服务器上。无法使用 content:// Uri 创建文件。
那么,在 Android 10 及更高版本中拾取图像并将其上传到服务器的标准方法是什么,并具有适当的范围存储。
编辑 这是一个图像文件,我必须在将其上传到服务器之前减小其大小。甚至大小减少功能也失败,因为它无法找到文件。
解决方法
创建一个临时文件并将uri的输入流复制到临时文件中
private val galleryLauncher =
registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) {
val tempFile = File.createTempFile("TempFile",".jpg",externalCacheDir)
val inputStream: InputStream? = contentResolver.openInputStream(uri)
if(inputStream != null) {
FileOutputStream(tempFile,false).use { outputStream ->
var read: Int
val bytes = ByteArray(DEFAULT_BUFFER_SIZE)
while (inputStream.read(bytes).also { read = it } != -1) {
outputStream.write(bytes,read)
}
outputStream.close()
}
inputStream.close()
//saved the tempfile's path for future reference
}
}
}
现在将通过临时文件的路径进行图像预览、压缩图像大小和上传图像。