Created
June 24, 2015 04:39
-
-
Save cdmckay/4b269e9017a30111556a to your computer and use it in GitHub Desktop.
Add support for MultipartFormData to the Play Scala WS library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utilities | |
import java.io.{ByteArrayOutputStream, File} | |
import com.ning.http.client.FluentCaseInsensitiveStringsMap | |
import com.ning.http.multipart.{MultipartRequestEntity, FilePart, StringPart} | |
import play.api.http.HeaderNames._ | |
import play.api.http.{ContentTypeOf, Writeable} | |
import play.api.mvc.{Codec, MultipartFormData} | |
object MultipartFormDataWriteable { | |
implicit def contentTypeOf_MultipartFormData[A](implicit codec: Codec): ContentTypeOf[MultipartFormData[A]] = { | |
ContentTypeOf[MultipartFormData[A]](Some("multipart/form-data; boundary=__X_PROCESS_STREET_BOUNDARY__")) | |
} | |
implicit def writeableOf_MultipartFormData(implicit contentType: ContentTypeOf[MultipartFormData[File]]): Writeable[MultipartFormData[File]] = { | |
Writeable[MultipartFormData[File]]((formData: MultipartFormData[File]) => { | |
val stringParts = formData.dataParts flatMap { | |
case (key, values) => values map (new StringPart(key, _)) | |
} | |
val fileParts = formData.files map { filePart => | |
new FilePart(filePart.key, filePart.ref, filePart.contentType getOrElse "application/octet-stream", null) | |
} | |
val parts = stringParts ++ fileParts | |
val headers = new FluentCaseInsensitiveStringsMap().add(CONTENT_TYPE, contentType.mimeType.get) | |
val entity = new MultipartRequestEntity(parts.toArray, headers) | |
val outputStream = new ByteArrayOutputStream | |
entity.writeRequest(outputStream) | |
outputStream.toByteArray | |
})(contentType) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment