android kotlin 上传文件 上传图片

kotlin 上传图片 首先要引入retrofig2


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'

读写权限


    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

上传图片要通过okhttp3  和 Reqest MultipartBody 两个类实现

本篇文章实现的过程类似模拟前端form表单提交 所以MultipartBody.build一定要加

.setType(MultipartBody.FORM)

否则后面的参数 addFormDataPart()是无效的 下面直接上代码 希望大家不要一味的 cv大法 多看源码

fun clientOkHttp(POST_IMAGE:String,FILE_IMAGE: ByteArray){
        val client = OkHttpClient()

        val requestBody = MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                //携带一个表单参数
                .addFormDataPart("username", "Chen-XiaoMo")
                //设置参数名、文件名和文件                     
   .addFormDataPart("myfile","Naruto.jpg",ProgressRequestBody(MediaType.parse("image/*"),
                        FILE_IMAGE, listener))
                .build()

        //val requestBody=MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("tset","tset").build()


        val request = Request.Builder()
                .url(POST_IMAGE)
                .post(requestBody)
                .build()
        val call = client.newCall(request)
        try {
            val response = call.execute()
            if (response.isSuccessful) {
                val body = response.body()
                Log.i("kang","asdjlajslkdjasd=21="+body!!.string())
                //val string = body!!.string()
            }
            response.close()
        }catch (e:Exception){
            Log.i("kang","错误="+e.toString())
        }
    }

    /**
     * Btimap转数组
     */
    fun btimapToBtyes(bitmap: Bitmap): ByteArray {
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        return baos.toByteArray()
    }
class ProgressRequestBody(private val contentType: MediaType?,
                          private val file: ByteArray,
                          private val listener: ProgressListener) : RequestBody() {
    override fun contentType(): MediaType? {
        return contentType
    }
    override fun contentLength(): Long {
        return file.size.toLong()
    }
    override fun writeTo(sink: BufferedSink) {
        try {
            val max = contentLength()
            var current = 0L
            //listenser做监听 这里我只放到这里 不写监听了 这个参数可以不用
            listener.onStart()
            //写入文件
            sink.write(file)
            listener.onComplete()
        } catch (e: Exception) {
            listener.onError(e)
        }
    }
}

 

你可能感兴趣的:(android,kotlin,图片上传)