找不到Kotlin改装上传图片

时间:2019-01-22 16:57:23

标签: android kotlin retrofit2

我正尝试从图库中发送照片,但出现错误,指示找不到图片

请求甚至没有发送到服务器

片段

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
        when (requestCode) {
            REQUEST_SELECT_IMAGE_IN_ALBUM -> {
                val contentURI = data!!.data
                postServer(contentURI)

            }
        }
    }
}

private fun postServer(contentURI: Uri) {

    val MEDIA_TYPE_IMAGE: MediaType = MediaType.parse("image/*")!!
    val file = File(contentURI.path)
    val requestBody: RequestBody = RequestBody.create(MEDIA_TYPE_IMAGE, file)
    mercrediViewModel.uploadImage(enfant, requestBody)
}

在我的模型中

fun uploadImage(enfant: Enfant, requestBody: RequestBody) {
    viewModelScope.launch {

        val request = mercrediService.uploadImage("****", enfant.id, requestBody)
        request.enqueue(object : Callback<ResponseBody> {
            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                Timber.i(" error image" + t)
            }

            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                Timber.i(" response image" + response.body())
            }

        })
    }
}

改造服务

@Multipart
@POST("api/update/enfant/photo/{id}")
fun uploadImage(
    @Header("X-AUTH-TOKEN") token: String?,
    @Path("id") id: Int,
    @Part("image") image: RequestBody
): Call<ResponseBody>

我有这个错误

好,谢谢,我已经更改了此错误消息是相同的:

I / MercrediViewModel $ uploadImage:zeze错误图像     java.io.FileNotFoundException:/ document / image:74(无此类文件或目录)         在java.io.FileInputStream.open(本机方法)         在java.io.FileInputStream。(FileInputStream.java:146)         在okio.Okio.source(Okio.java:168)         在okhttp3.RequestBody $ 3.writeTo(RequestBody.java:119)         在okhttp3.MultipartBody.writeOrCountBytes(MultipartBody.java:173)         在okhttp3.MultipartBody.writeTo(MultipartBody.java:114)         .....

谢谢

1 个答案:

答案 0 :(得分:1)

最后我的解决方案

class FileHelper {

fun createFile(realPath: String): File {
    return File(realPath)
}

fun createRequestBody(file: File): RequestBody {
    val MEDIA_TYPE_IMAGE: MediaType = MediaType.parse("image/*")!!
    return RequestBody.create(MEDIA_TYPE_IMAGE, file)
}

fun createPart(file: File, requestBody: RequestBody): MultipartBody.Part {
    return MultipartBody.Part.createFormData("image", file.name, requestBody)
}

fun getPathFromURI(context: Context, uri: Uri): String? {
    val path: String = uri.path
    var realPath: String? = null

    val databaseUri: Uri
    val selection: String?
    val selectionArgs: Array<String>?
    if (path.contains("/document/image:")) { // files selected from "Documents"
        databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        selection = "_id=?"
        selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
    } else { // files selected from all other sources, especially on Samsung devices
        databaseUri = uri
        selection = null
        selectionArgs = null
    }
    try {
        val projection = arrayOf(
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media._ID,
            MediaStore.Images.Media.ORIENTATION,
            MediaStore.Images.Media.DATE_TAKEN
        ) // some example data you can query
        val cursor = context.contentResolver.query(
            databaseUri,
            projection, selection, selectionArgs, null
        )
        if (cursor.moveToFirst()) {
            val columnIndex = cursor.getColumnIndex(projection[0])
            realPath = cursor.getString(columnIndex)
        }
        cursor.close()
    } catch (e: Exception) {
        Timber.i("zeze get path error " + e.message)
    }
    return realPath
}

}

@Multipart
@POST("api/update/enfant/photo/{id}")
fun uploadImage(
    @Path("id") enfantId: Int,
    @Part file: MultipartBody.Part,
    @Part("image") requestBody: RequestBody): Call<ResponseBody>