如何在Retrofit 2 Kotlin中的post参数中发送任何类型的File?

时间:2019-06-10 12:48:43

标签: android kotlin retrofit2 multipart

让我分享一些我已经实现的在请求中发送图像文件的代码。

以下是我对api请求的功能:

@Multipart
@POST("api/order/order_create")
fun createOrder(
    @Header("Authorization") authorization: String?,
    @Part("category_id") categoryId: RequestBody?,
    @Part("size") size: RequestBody?,
    @Part("narration") narration: RequestBody?,
    @Part("ref_picture") file: RequestBody?
): Call<OrderCreateResponse>

以下是我通过发送必要的参数调用api的代码:

var fbody = RequestBody.create(MediaType.parse("image/*"), imageFile)
var size = RequestBody.create(MediaType.parse("text/plain"), et_custom_order_size.text.toString())
var catId = RequestBody.create(MediaType.parse("text/plain"), selectedID.toString())
var narration = RequestBody.create(MediaType.parse("text/plain"),et_custom_order_narration.text.toString())

val orderCreateAPI = apiService!!.createOrder(complexPreferences?.getPref("token", null), catId,size,narration,fbody)

通过以下方法获取imageFile,

imageFile = File(Global.getRealPathFromURI(activity!!, imageUri!!))

使用下面的函数获取真实路径,

fun getRealPathFromURI(context: Context, contentUri: Uri): String {
        var cursor: Cursor? = null
        try {
            val proj = arrayOf(MediaStore.Images.Media.DATA)
            cursor = context.contentResolver.query(contentUri, proj, null, null, null)
            val column_index = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            cursor.moveToFirst()
            return cursor.getString(column_index)
        } catch (e: Exception) {
            Log.e(TAG, "getRealPathFromURI Exception : " + e.toString())
            return ""
        } finally {
            if (cursor != null) {
                cursor.close()
            }
        }
    }

通过以上述方式发送图像,我将无法发送图像!请同样指导我。 预先感谢。

3 个答案:

答案 0 :(得分:0)

尝试更改
@Part("ref_picture") file: RequestBody?

@Part("ref_picture") file: MultipartBody.Part?

然后做

// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)),file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

您也可以检查此答案 https://stackoverflow.com/a/34562971/8401371

答案 1 :(得分:0)

@Multipart
@POST("register")
Observable<SignInResponse> signUp(@Part("name") RequestBody name, @Part MultipartBody.Part fileToUpload);

然后将图像文件作为MultipartBody.Part变量传递

// image as file
    var body: MultipartBody.Part? = null
    if (!profileImagePath.isNullOrBlank()) {
        val file = File(profileImagePath)
        val inputStream = contentResolver.openInputStream(Uri.fromFile(file))
        val requestFile = RequestBody.create(MediaType.parse("image/jpeg"), getBytes(inputStream))
        body = MultipartBody.Part.createFormData("image", file.name, requestFile)
        Log.d("nama file e cuk", file.name)
    }

最后可以让RequestBody变

RequestBody.create(MediaType.parse("text/plain"), user_full_name)

最终发送请求:)

答案 2 :(得分:0)

您可以这样操作:

    var propertyImagePart: MultipartBody.Part? = null
            imageUrl.value?.let {
                val propertyImageFile = File(FILE_PATH)
                val propertyImage: RequestBody = RequestBody.create(MediaType.parse("image/*"), propertyImageFile)
                propertyImagePart =MultipartBody.Part.createFormData("userImage", propertyImageFile.name, propertyImage)
            }

    job = launch {
            try {
                val response = apiServiceWithoutHeader.doUpdateProfile(propertyImagePart,profileRequest.getMultipart()).await()
                stateLiveData.postValue(UserProfileState.SuccessUpdateProfile(response))
            } catch (e: JsonSyntaxException) {
                onException(e)
            } catch (e: JsonParseException) {
                onException(e)
            } catch (e: IOException) {
                onException(e)
            } catch (e: HttpException) {
                onException(e)
            }
        }