简体   繁体   中英

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

Let me share some of my code which i have implemented to send image file in the request.

Below is my function of api request:

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

Below is the code where i am calling the api by sending the necessary parameters:

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)

Here imageFile is fetched by the below way,

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

Using below function to get the real path,

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

By sending image in the above way, i am not able to send it! Please guide me with the same. Thanks in advance.

Try changing
@Part("ref_picture") file: RequestBody?
to
@Part("ref_picture") file: MultipartBody.Part?

And do this

// 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);

You may also check this answer https://stackoverflow.com/a/34562971/8401371

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

Then pass image file as MultipartBody.Part variable

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

Last thing you can make RequestBody var

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

finally send request :)

You can do this like this way :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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