欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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