将图像从Android上载到仅接受JPEG和PNG的服务器

问题描述 投票:0回答:2

MediaStore.Images.Media.Data已过时,因此我尝试使用字节数组,但是我的服务器抛出一个错误,它仅接受jpeg和png文件类型。我已经从其他问题中多次阅读@commonsware的答案,但我似乎无法正确理解。如何获取文件类型以及图像,以便可以将其附加到网络呼叫中?在此先感谢

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == RESULT_OK && requestCode == PROFILE_REQUEST_CODE) {
            val uri = data?.data
            createImageData(uri)
            profile_image.setImageURI(data?.data)
        }
    }
 private fun createImageData(uri: Uri?) {
        val inputStream = activity?.contentResolver?.openInputStream(uri!!)
        processImage(inputStream)
    }

    private fun processImage(inputStream: InputStream?) {
        imageData = inputStream?.readBytes()
        bitmap = BitmapFactory.decodeStream(inputStream)
        val imageBody: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), imageData!!)
        val image: MultipartBody.Part = MultipartBody.Part.createFormData("image", "user", imageBody)
        uploadImage(image)
    }

    private fun uploadImage(image: MultipartBody.Part) {
        val user = appPreferences?.getUser()
        val userToken = user?.jwt_token
        val token = "Bearer $userToken"
        val headers = HashMap<String, String>()

        //headers["Authorization"] = token
        val uploadResponseCall: Call<ProfileImageResponse> = client.getApi().upload(token, image)
        uploadResponseCall.enqueue(object : retrofit2.Callback<ProfileImageResponse> {
            override fun onResponse(call: Call<ProfileImageResponse>, response: Response<ProfileImageResponse>) {
                val imageResponse = response.body()
                val resCode = imageResponse?.statuscode
                val msg = imageResponse?.message
                if (resCode == 200) {
                    appUtils.showSnackBar(requireActivity().applicationContext, profile_frame, msg!!)
                } else {
                    appUtils.showSnackBar(requireActivity().applicationContext, profile_frame, "wrong file type")
                }
            }

            override fun onFailure(call: Call<ProfileImageResponse>, t: Throwable) {
                if (t is IOException) {
                    call.cancel()
                    Log.d("profilefragment", "issue")
                    appUtils.showSnackBar(requireActivity().applicationContext, profile_frame, "server error")
                }
            }
        })

    }
android arrays kotlin retrofit inputstream
2个回答
0
投票

尝试添加适当的Content-Type标头。 image/pngimage/jpg应该合适。


0
投票

这里是示例

© www.soinside.com 2019 - 2024. All rights reserved.