Skip to content
Console

Upload and download on Android

Do not embed an AccessKey in a mobile app; the installation package can be decompiled. The recommended approach is for the app to request a presigned URL from your server and then upload directly to S4. For how the server issues URLs, see the examples for Node.js, Go, Java, and other languages, or use the Node.js server in the browser example directly.

This way the app only makes plain HTTP requests and does not need to integrate the AWS SDK.

Install

build.gradle.kts
implementation("com.squareup.okhttp3:okhttp:4.12.0")

Declare the network permission in AndroidManifest.xml:

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

Request an upload URL

S4.kt
/** Request an upload URL from your server; returns JSON: {"key": "...", "url": "..."} */
fun requestTicket(filename: String, size: Long): String {
    // filename comes from the user; in production code, serialize with a JSON library
    val json = """{"filename":"$filename","size":$size}"""
    val request = Request.Builder()
        .url("https://api.example.com/upload/single")
        // Add your own login credentials here
        .post(json.toRequestBody("application/json".toMediaType()))
        .build()
    http.newCall(request).execute().use { response ->
        if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
        return response.body!!.string()
    }
}

Upload files

S4.kt
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okio.BufferedSink
import okio.source

class S4Exception(val status: Int, val code: String?) : IOException("S4 $status $code")

val http = OkHttpClient.Builder()
    .writeTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .build()

/** A file request body that reports progress */
class FileBody(
    private val file: File,
    private val type: MediaType?,
    private val onProgress: (Float) -> Unit,
) : RequestBody() {
    override fun contentType() = type
    override fun contentLength() = file.length()

    override fun writeTo(sink: BufferedSink) {
        var sent = 0L
        file.source().use { source ->
            while (true) {
                val n = source.read(sink.buffer, 64 * 1024)
                if (n == -1L) break
                sink.emitCompleteSegments()
                sent += n
                onProgress(sent.toFloat() / file.length())
            }
        }
    }
}

/** Upload a file to the presigned URL and return the ETag. Call from a background thread */
fun upload(
    file: File,
    url: String,
    contentType: String? = null, // Pass this only if it was specified when signing; it must match exactly
    onProgress: (Float) -> Unit = {},
): String? {
    val request = Request.Builder()
        .url(url)
        .put(FileBody(file, contentType?.toMediaType(), onProgress))
        .build()
    http.newCall(request).execute().use { response ->
        if (!response.isSuccessful) {
            val code = Regex("<Code>(.*?)</Code>").find(response.body?.string().orEmpty())
            throw S4Exception(response.code, code?.groupValues?.get(1))
        }
        return response.header("ETag")
    }
}

Call it from a coroutine:

UploadViewModel.kt
viewModelScope.launch {
    val etag = withContext(Dispatchers.IO) {
        upload(file, ticketUrl) { progress -> _progress.value = progress }
    }
}

To upload a file at a content:// URI, first copy it to the cache directory with contentResolver.openInputStream(uri), or modify FileBody to read from the input stream. For uploads that must continue in the background, use WorkManager.

Download files

S4.kt
/** Download to a local file. Call from a background thread */
fun download(url: String, target: File) {
    http.newCall(Request.Builder().url(url).build()).execute().use { response ->
        val body = response.body
        if (!response.isSuccessful || body == null) throw S4Exception(response.code, null)
        target.outputStream().use { out -> body.byteStream().copyTo(out) }
    }
}

Public files and files on a CDN do not need signing; load the URL directly with Coil or Glide. You can also add CoreIX parameters to fetch thumbnails sized to the screen.

The aws-android-sdk-s3 (AWS Android SDK v2) mentioned in earlier docs is no longer updated and is not recommended.

FAQ

Upload returns 403 SignatureDoesNotMatch
  • If ContentType was specified when signing, the upload must send the same value; if it was not, no value is required;
  • If ContentLength was specified when signing, the file size must match;
  • Do not encode the URL a second time.
Upload returns 403 AccessDenied

The URL has expired, or the sub-user that issued it has no write permission. The phone clock does not affect presigned URLs, but the server clock does.

How do I upload large files

Have your server create the multipart upload and issue a URL for each part. The app reads the file one segment at a time, PUTs each part, records each part's ETag, and finally the server completes the upload. The flow is the same as browser multipart upload.

Downloading an installer package (apk, ipa) returns 403

S4 direct connections cannot serve these two file types. Use a CDN domain instead.