Transferring large files (camera photos, videos, PDF documents) over mobile networks requires robust engineering. If a user walks into an elevator and loses Wi-Fi mid-upload, the app must not crash or discard the transfer. In this class, we build resilient Multipart file uploads and background transfers powered by WorkManager.
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
interface FileUploadApiService {
@retrofit2.http.Multipart
@retrofit2.http.POST("v1/files/upload")
suspend fun uploadDocument(
@retrofit2.http.Part filePart: MultipartBody.Part
): Response<UploadResult>
}
fun prepareFilePart(file: File): MultipartBody.Part {
val requestBody = file.asRequestBody("image/jpeg".toMediaTypeOrNull())
return MultipartBody.Part.createFormData("file", file.name, requestBody)
}
By executing uploads inside a CoroutineWorker, Android guarantees that the file upload continues even if the user leaves the application or restarts their device:
class UploadFileWorker(
context: Context,
params: WorkerParameters
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val filePath = inputData.getString("FILE_PATH") ?: return Result.failure()
val file = File(filePath)
return try {
val filePart = prepareFilePart(file)
val response = apiService.uploadDocument(filePart)
if (response.isSuccessful) Result.success() else Result.retry()
} catch (e: Exception) {
Result.retry()
}
}
}
Broaden your foundational and advanced Android application development skills across our curriculum:
Configure constraints (unmetered WiFi, battery charging) for jobs.
Build MultipartBody.Part requests for photos and documents.
Pick user files securely using ActivityResultContracts.PickVisualMedia.
Save downloaded files to public Download directory via MediaStore.