Multipart File Uploads, Downloads & WorkManager

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.

Multipart Form Uploads with Retrofit & OkHttp

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

Guaranteed Background Uploads via CoroutineWorker

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

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. How do I show upload progress percentage in a system notification?

Inside your `CoroutineWorker`, invoke `setProgressAsync(workDataOf("PROGRESS" to percentage))` and update a foreground status notification via `setForeground(createForegroundInfo(percentage))`.

Q2. What is Android's built-in DownloadManager?

`DownloadManager` is a system service that handles long-running HTTP downloads in the background, managing network transitions, retries, and broadcasting `ACTION_DOWNLOAD_COMPLETE` upon finishing.

Q3. How should I select files from device storage in modern Android?

Use the **Android Photo Picker** via `ActivityResultContracts.PickVisualMedia()` for images and videos, or `ActivityResultContracts.GetContent()` for general documents. This eliminates the need to request dangerous storage permissions.

Explore Related Android Development Classes & Next Steps

Broaden your foundational and advanced Android application development skills across our curriculum:

Services vs. Jetpack WorkManager

Configure constraints (unmetered WiFi, battery charging) for jobs.

Retrofit 2 Multipart Uploads

Build MultipartBody.Part requests for photos and documents.

Runtime Permissions & Photo Picker

Pick user files securely using ActivityResultContracts.PickVisualMedia.

ContentProviders & Scoped Storage

Save downloaded files to public Download directory via MediaStore.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!