Skip to content

Instantly share code, notes, and snippets.

@hoc081098
Created September 21, 2022 08:19
Show Gist options
  • Save hoc081098/58bb431273879b9ccd018078cbbf81cd to your computer and use it in GitHub Desktop.
Save hoc081098/58bb431273879b9ccd018078cbbf81cd to your computer and use it in GitHub Desktop.
suspend fun upload(uri: Uri) {
val contentResolver = applicationContext.contentResolver
val bytes = contentResolver
.openInputStream(uri)
?.use { inputStream -> inputStream.buffered().use { it.readBytes() } }
checkNotNull(bytes)
val type = contentResolver.getType(uri)
checkNotNull(type)
val fileName = contentResolver.query(uri, null, null, null, null)?.use {
it.moveToFirst()
it.getString(it.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
}
val file = MultipartBody.Part.createFormData(
name = "file",
filename = fileName,
body = bytes.toRequestBody(type.toMediaTypeOrNull())
)
apiService.uploadFile(
file = file,
imageName = ""
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment