het*_*dhi 6 android multipart kotlin retrofit2
让我分享一些我已经实现的代码,用于在请求中发送图像文件。
下面是我的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>
Run Code Online (Sandbox Code Playgroud)
下面是我通过发送必要的参数来调用 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)
Run Code Online (Sandbox Code Playgroud)
这里 imageFile 是通过以下方式获取的,
imageFile = File(Global.getRealPathFromURI(activity!!, imageUri!!))
Run Code Online (Sandbox Code Playgroud)
使用下面的函数来获取真实路径,
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()
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过以上方式发送图片,我无法发送!请指导我同样的事情。提前致谢。
尝试更改
@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);
Run Code Online (Sandbox Code Playgroud)
您也可以检查这个答案 /sf/answers/2419408001/
| 归档时间: |
|
| 查看次数: |
7844 次 |
| 最近记录: |