Skip to content

Commit

Permalink
MultipartWritable - adding an extension-implied content type (expecte…
Browse files Browse the repository at this point in the history
…d by Azure file upload)
  • Loading branch information
peterbanda committed Dec 21, 2023
1 parent 16a2690 commit 5104e3a
Showing 1 changed file with 32 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,27 @@ object MultipartWritable {
val CONTENT_TYPE = "content-type"
}

private val fileExtensionContentTypeMap = Map(
"txt" -> "text/plain",
"csv" -> "text/csv",
"json" -> "application/json",
"xml" -> "application/xml",
"pdf" -> "application/pdf",
"zip" -> "application/zip",
"tar" -> "application/x-tar",
"gz" -> "application/x-gzip",
"ogg" -> "application/ogg",
"mp3" -> "audio/mpeg",
"wav" -> "audio/x-wav",
"mp4" -> "video/mp4",
"webm" -> "video/webm",
"png" -> "image/png",
"jpg" -> "image/jpeg",
"jpeg" -> "image/jpeg",
"gif" -> "image/gif",
"svg" -> "image/svg+xml"
)

/**
* `Writeable` for `MultipartFormData`.
*/
Expand All @@ -45,13 +66,21 @@ object MultipartWritable {

def filePartHeader(file: FilePart) = {
val name = s""""${file.key}""""
val filename = s""""${file.headerFileName.getOrElse(file.path)}""""
val contentType = file.contentType.map { ct =>
val filenameAux = file.headerFileName.getOrElse(file.path)
val filenamePart = s""""${filenameAux}""""

val contentTypeAux = file.contentType.orElse {
val extension = filenameAux.split('.').last
// Azure expects an explicit content type for files
fileExtensionContentTypeMap.get(extension)
}

val contentTypePart = contentTypeAux.map { ct =>
s"${HttpHeaderNames.CONTENT_TYPE}: $ct\r\n"
}.getOrElse("")

encode(
s"--$boundary\r\n${HttpHeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filename\r\n$contentType\r\n"
s"--$boundary\r\n${HttpHeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filenamePart\r\n$contentTypePart\r\n"
)
}

Expand Down

0 comments on commit 5104e3a

Please sign in to comment.