【问题标题】:how to upload image file from ImageView to nodejs server (multer) using okhttp? Kotlin如何使用 okhttp 将图像文件从 ImageView 上传到 nodejs 服务器(multer)?科特林
【发布时间】:2019-07-29 02:50:31
【问题描述】:

我已经编写了使用okhttp和kotlin将图像上传到服务器的代码,即用户通过相机拍照然后当用户单击发送按钮时将图像显示在imageView中,我想要ImageView中的图像要发送到服务器,但我不知道如何将 ImageView 中的图像更改为可以发送到服务器的文件,请参阅我的代码了解更多详情

这是我的 kotlin 代码

 fun uploadImage(url:String, image:File, imageName:String){
    val MEDIA_TYPE_PNG = MediaType.parse("image/png")
    val client = OkHttpClient()

    val requestBody = MultipartBody.Builder().setType(MultipartBody.FORM)
        .addFormDataPart("file", imageName, RequestBody.create(MEDIA_TYPE_PNG, image))
        .build()

    val request = Request.Builder()
        .url(url)
        .post(requestBody)
        .build()

    client.newCall(request).enqueue(object:Callback{
        override fun onFailure(call: Call, e: IOException) {

        }

        override fun onResponse(call: Call, response: Response) {
            Log.i(TAG,"response ${response.body?.string()}")
        }
    })
}

问题是,如何将 imageView 中的图片转换为 "image:File" 用于 uploadImage 功能?

【问题讨论】:

    标签: android node.js kotlin multer okhttp3


    【解决方案1】:

    希望有帮助

        val url = getString(R.string.urlUpload)
        val MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg")
    
        val bitmap = (img_register.drawable as BitmapDrawable).bitmap
          val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
       val bitmapByteArray = baos.toByteArray()
      val file = Base64.encodeToString(bitmapByteArray,Base64.DEFAULT)
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多