Short answer: to upload an image with Retrofit, declare a @Multipart endpoint with a @Part MultipartBody.Part for the file, turn the image into a RequestBody with a media type, wrap it with MultipartBody.Part.createFormData, and call the suspend function from a coroutine.
This guide uses Kotlin, coroutines and the Android Photo Picker, so you do not need storage permissions to select an image.
Step 1: Add dependencies
dependencies {
implementation("com.squareup.retrofit2:retrofit:RETROFIT_VERSION")
implementation("com.squareup.retrofit2:converter-gson:RETROFIT_VERSION")
implementation("com.squareup.okhttp3:okhttp:OKHTTP_VERSION")
}
Use the latest stable versions from the official Retrofit and OkHttp pages. Add the INTERNET permission to your manifest.
Step 2: Define the API
data class UploadResponse(val url: String)
interface UploadApi {
@Multipart
@POST("upload")
suspend fun uploadImage(
@Part image: MultipartBody.Part,
@Part("description") description: RequestBody
): Response<UploadResponse>
}
The part name "image" (set in Step 4) must match what your server expects. Replace upload with your real endpoint.
Step 3: Create the Retrofit instance
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val uploadApi = retrofit.create(UploadApi::class.java)
Step 4: Turn the picked image into a multipart request
Images chosen with the Photo Picker come back as a content Uri, not a file path. Copy it to your cache directory first, then create the parts:
fun copyUriToCache(context: Context, uri: Uri): File {
val file = File(context.cacheDir, "upload_" + System.currentTimeMillis() + ".jpg")
context.contentResolver.openInputStream(uri)?.use { input ->
file.outputStream().use { output -> input.copyTo(output) }
}
return file
}
suspend fun uploadImage(context: Context, uri: Uri): Result<String> {
return try {
val file = withContext(Dispatchers.IO) { copyUriToCache(context, uri) }
val requestFile = file.asRequestBody("image/*".toMediaTypeOrNull())
val body = MultipartBody.Part.createFormData("image", file.name, requestFile)
val description = "Profile photo".toRequestBody("text/plain".toMediaTypeOrNull())
val response = uploadApi.uploadImage(body, description)
if (response.isSuccessful) {
Result.success(response.body()?.url ?: "")
} else {
Result.failure(Exception("Upload failed: " + response.code()))
}
} catch (e: IOException) {
Result.failure(e)
}
}
Required imports include okhttp3.MediaType.Companion.toMediaTypeOrNull, okhttp3.RequestBody.Companion.asRequestBody, okhttp3.RequestBody.Companion.toRequestBody and okhttp3.MultipartBody.
Step 5: Pick an image in Jetpack Compose
@Composable
fun UploadScreen() {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var status by remember { mutableStateOf("Choose an image") }
val picker = rememberLauncherForActivityResult(
ActivityResultContracts.PickVisualMedia()
) { uri ->
if (uri != null) {
status = "Uploading..."
scope.launch {
val result = uploadImage(context, uri)
status = result.fold(
onSuccess = { "Uploaded: " + it },
onFailure = { "Error: " + it.message }
)
}
}
}
Column(Modifier.padding(16.dp)) {
Button(onClick = {
picker.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
}) { Text("Pick and upload") }
Text(status)
}
}
In a real app, put the upload call in a ViewModel and expose the result as state. See our MVVM tutorial.
Upload several images
Declare the parameter as @Part images: List<MultipartBody.Part> and give each part the same field name your server expects (often images[] or images). Check your backend’s documentation.
Common errors and fixes
- HTTP 400 or 422 from the server. The part name does not match. Compare it with the server’s field name.
- HTTP 413 (payload too large). Compress or resize the image before upload, and check the server’s size limit.
- FileNotFoundException with a content Uri. Do not use
Uri.pathas a file path. Copy the content with the content resolver as shown. - NetworkOnMainThreadException. Run file copying on
Dispatchers.IOand call Retrofit suspend functions from a coroutine. - Cleartext HTTP not permitted. Use HTTPS for your API.
FAQ
How do I upload a file with Retrofit?
Use @Multipart with @Part MultipartBody.Part and build the part with MultipartBody.Part.createFormData(name, fileName, requestBody).
Do I need storage permission to pick an image?
Not with the Photo Picker (PickVisualMedia). The system gives your app access only to the chosen image.
How do I show upload progress?
Wrap the RequestBody in a custom body that reports bytes written, or use a library or WorkManager for large uploads.
Can I send extra fields with the image?
Yes. Add more @Part("name") RequestBody parameters, as the description is sent above.
More Android guides: Android tutorials for beginners.