or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

caching.mdcookies.mdforms-multipart.mdhttp-client.mdindex.mdinterceptors.mdnetworking.mdrequests-responses.mdsecurity.mdurls.mdwebsockets.md

forms-multipart.mddocs/

0

# Form and Multipart Handling

1

2

Form data and multipart request body construction for file uploads and form submissions.

3

4

## FormBody

5

6

For application/x-www-form-urlencoded requests.

7

8

```kotlin { .api }

9

class FormBody private constructor() : RequestBody() {

10

val size: Int

11

fun encodedName(index: Int): String

12

fun name(index: Int): String

13

fun encodedValue(index: Int): String

14

fun value(index: Int): String

15

16

class Builder {

17

fun add(name: String, value: String): Builder

18

fun addEncoded(name: String, value: String): Builder

19

fun build(): FormBody

20

}

21

}

22

```

23

24

## MultipartBody

25

26

For multipart/form-data requests, typically used for file uploads.

27

28

```kotlin { .api }

29

class MultipartBody private constructor() : RequestBody() {

30

val type: MediaType

31

val boundary: String

32

val size: Int

33

fun part(index: Int): Part

34

fun parts(): List<Part>

35

36

class Builder {

37

constructor()

38

constructor(boundary: String)

39

40

fun setType(type: MediaType): Builder

41

fun addPart(body: RequestBody): Builder

42

fun addPart(headers: Headers?, body: RequestBody): Builder

43

fun addFormDataPart(name: String, value: String): Builder

44

fun addFormDataPart(name: String, filename: String?, body: RequestBody): Builder

45

fun build(): MultipartBody

46

}

47

48

class Part private constructor() {

49

val headers: Headers?

50

val body: RequestBody

51

52

companion object {

53

fun create(body: RequestBody): Part

54

fun create(headers: Headers?, body: RequestBody): Part

55

fun createFormData(name: String, value: String): Part

56

fun createFormData(name: String, filename: String?, body: RequestBody): Part

57

}

58

}

59

60

companion object {

61

val MIXED: MediaType

62

val ALTERNATIVE: MediaType

63

val DIGEST: MediaType

64

val PARALLEL: MediaType

65

val FORM: MediaType

66

}

67

}

68

```

69

70

### File Upload Example

71

72

```kotlin

73

val file = File("photo.jpg")

74

val requestBody = file.asRequestBody("image/jpeg".toMediaType())

75

76

val multipartBody = MultipartBody.Builder()

77

.setType(MultipartBody.FORM)

78

.addFormDataPart("title", "My Photo")

79

.addFormDataPart("photo", "photo.jpg", requestBody)

80

.build()

81

82

val request = Request.Builder()

83

.url("https://api.example.com/upload")

84

.post(multipartBody)

85

.build()

86

```