# Upload and download on Android

> Connect to Bitiful S4 on Android with OkHttp and presigned URLs: Kotlin examples for uploads with progress, downloads, and error handling.

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](https://docs.bitiful.com/en/developer/sdk/nodejs-demo/start-to-use.md), [Go](https://docs.bitiful.com/en/developer/sdk/golang-demo/start-to-use.md), [Java](https://docs.bitiful.com/en/developer/sdk/java-demo/start-to-use.md), and other languages, or use the Node.js server in the [browser example](https://docs.bitiful.com/en/developer/sdk/browser-demo/start-to-use.md) directly.

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

## Install

```kotlin title="build.gradle.kts"
implementation("com.squareup.okhttp3:okhttp:4.12.0")
```

Declare the network permission in `AndroidManifest.xml`:

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

## Request an upload URL

```kotlin title="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

```kotlin title="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:

```kotlin title="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

```kotlin title="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](https://docs.bitiful.com/en/coreix/basic.md) to fetch thumbnails sized to the screen.

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

## FAQ

<details>
<summary>Upload returns 403 SignatureDoesNotMatch</summary>

- 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.

</details>

<details>
<summary>Upload returns 403 AccessDenied</summary>

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.

</details>

<details>
<summary>How do I upload large files</summary>

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](https://docs.bitiful.com/en/developer/sdk/browser-demo/start-to-use.md).

</details>

<details>
<summary>Downloading an installer package (apk, ipa) returns 403</summary>

S4 direct connections cannot serve these two file types. Use a [CDN domain](https://docs.bitiful.com/en/cdn/intro.md) instead.

</details>

## Related documentation

[**Presigned URLs and extensions**](https://docs.bitiful.com/en/developer/s3/presigned-url.md)

Full reference for request limits, rate limits, Simul-Transfer, and other parameters.

[**Error codes and troubleshooting**](https://docs.bitiful.com/en/developer/s3/errors.md)

Checklists for 403, SignatureDoesNotMatch, and other issues.

[**S3 API compatibility**](https://docs.bitiful.com/en/developer/s3/compatibility.md)

Support status and differences for each operation.

[**Upload files securely from the client**](https://docs.bitiful.com/en/best-practice/web-uploads.md)

Recommended practices for direct uploads from browsers and apps.
