繁体   English   中英

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

[英]How to send File of any type in post parameter in Retrofit 2 Kotlin?

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

以下是我的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()
            }
        }
    }

通过以上述方式发送图像,我无法发送它! 请指导我一样。 提前致谢。

尝试改变
@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

@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)

最后发送请求:)

你可以这样做:

    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)
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM