uri转RequestBody,uri转MultipartBody.Part
程序员文章站
2022-04-12 08:02:15
//uri转MultipartBody.Partfun Uri.asPart(name:String,context: Context):MultipartBody.Part{ val contentResolver = context.contentResolver val displayName = run { val cursor = contentResolver.query(this, null, null, null, null) cursor....
//uri转MultipartBody.Part
fun Uri.asPart(name:String,context: Context):MultipartBody.Part{
val contentResolver = context.contentResolver
val displayName = run {
val cursor = contentResolver.query(this, null, null, null, null)
cursor?.let {
if(it.moveToFirst())
it.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
else null
}
}?:"${System.currentTimeMillis()}.${MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(this))}"
return MultipartBody.Part.createFormData(name,displayName, asRequestBody(context))
}
//uri转requestBody
fun Uri.asRequestBody(context:Context):RequestBody = object :RequestBody(){
override fun contentType(): MediaType = MediaType.get(getMimeType(context))
override fun writeTo(sink: BufferedSink) {
val ips = context.contentResolver.openInputStream(this@asRequestBody)
ips?.let { sink.writeAll(Buffer().readFrom(it,contentLength())) }
}
override fun contentLength(): Long = context.contentResolver.openFileDescriptor(this@asRequestBody,"r")?.statSize?:0L
}
//返回文件的mimetype
fun Uri.getMimeType(context: Context) = context.contentResolver.getType(this)?:"multipart/form-data"
本文地址:https://blog.csdn.net/jingzz1/article/details/108577319
下一篇: CSS笔记-3:背景
推荐阅读
-
C#利用System.Uri转URL为绝对地址的方法
-
C#利用System.Uri转URL为绝对地址的方法
-
(转)@RequestParam、@RequestBody和@ModelAttribute区别
-
(转)@RequestParam、@RequestBody和@ModelAttribute区别
-
uri转RequestBody,uri转MultipartBody.Part
-
android 图片工具类 (图片压缩 图片长按缓存 Bitmap转Base64 Bitmap转File File转Bitmap 打开系统相册解析URI)
-
URI和URL的区别(转)
-
Android根据图片Uri获取图片path绝对路径的几种方法【转】
-
uri转RequestBody,uri转MultipartBody.Part
-
Uri转File Path(兼容Android 7.0+)