Skip to content

Commit

Permalink
Have generic dataparts using streams
Browse files Browse the repository at this point in the history
Should work for #344
Should work for #479
  • Loading branch information
SleeplessByte committed Oct 28, 2018
1 parent 63b0f72 commit 715dc99
Showing 1 changed file with 67 additions and 4 deletions.
71 changes: 67 additions & 4 deletions fuel/src/main/kotlin/com/github/kittinunf/fuel/core/DataPart.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,72 @@
package com.github.kittinunf.fuel.core

import java.io.File
import java.io.FileInputStream
import java.nio.charset.Charset

/**
* https://tools.ietf.org/html/rfc2183
*/
enum class ContentDispositionType(val value: String) {
INLINE("inline"),
ATTACHMENT("attachment"),
FORM_DATA("form-data")
}

data class DataPart(
val file: File,
val name: String = file.nameWithoutExtension,
val type: String = ""
)
val partName: String,
val fileName: String?,
val contentType: String?,
val type: ContentDispositionType,
val dataPartBody: Body
) : Body by dataPartBody {
companion object {
val DEFAULT_CONTENT_TYPE = "application/octet-stream"

fun from(
file: File,
length: Number? = null,
partName: String? = null,
fileName: String? = null,
contentType: String? = null,
charset: Charset = Charsets.UTF_8
): DataPart {

val calculateLength = when (charset == Charsets.UTF_8) {
true -> length?.let { { it } } ?: { file.length() }
false -> null
}

return from(
partName = partName ?: file.nameWithoutExtension,
fileName = fileName ?: file.name,
contentType = contentType,
dataPartBody = DefaultBody.from(
openStream = { FileInputStream(file) },
calculateLength = calculateLength,
charset = charset
)
)
}

fun from(partName: String, fileName: String? = null, contentType: String? = null, dataPartBody: Body) = DataPart(
partName = partName,
fileName = fileName,
contentType = contentType,
type = ContentDispositionType.FORM_DATA,
dataPartBody = dataPartBody
)

fun from(blob: Blob, fileName: String? = null, contentType: String? = null, charset: Charset = Charsets.UTF_8) = DataPart(
partName = blob.name,
fileName = fileName,
contentType = contentType,
type = ContentDispositionType.FORM_DATA,
dataPartBody = DefaultBody.from(
openStream = { blob.inputStream.invoke() },
calculateLength = { blob.length },
charset = charset
)
)
}
}

0 comments on commit 715dc99

Please sign in to comment.