1

I am using Play Framework 2.5.x with Scala

I need to expose a POST Endpoint where it is possible to post a Json and upload a file as part of the same Request.

As a requirement I need to use multipart/form-data

I cannot have any type of form as suggested in this link:

https://www.playframework.com/documentation/2.5.x/ScalaFileUpload#Direct-file-upload

How to do that?

Filipe Miranda
  • 914
  • 1
  • 20
  • 33
  • 1
    What does your request look like? As far as I know, the body of a request can only contain one bit of content. – irundaia Jun 25 '16 at 16:31
  • Hi @irundaia, it should contain: POST /endpoint { property: "property", property2: "value" } + File in multipartform – Filipe Miranda Jun 25 '16 at 16:37

1 Answers1

0

I guess this test case lines can explain it better

val part = FilePart[TemporaryFile](key = "picture", filename = "image.JPG", contentType = Some("image/jpeg"), ref = mockFile)
val data = Map("property1" -> "property1")
val formData: MultipartFormData[TemporaryFile] = MultipartFormData(dataParts = data, files = Seq(part), badParts = Seq(), missingFileParts = Seq())
val request = FakeRequest(POST, "/uploadFileWithJson").withMultipartFormDataBody(formData)

So if you want to pass data with file upload you can send it as Map like "data" in the above example and in actual controller side you can do like this:-

request.body.asMultipartFormData.get.dataParts

Above will contain the data Map

request.body.asMultipartFormData.get.file("picture")

This will contain the file.

Arpit Suthar
  • 754
  • 1
  • 5
  • 19
  • Your solution does not really work, if you pass the JSON as a String from a HTP client, it is not possible to get it back. I am using Play 2.5 case class MultipartFormData[A](dataParts: Map[String, Seq[String]], files: Seq[FilePart[A]], badParts: Seq[BadPart]) – Filipe Miranda Jul 04 '16 at 15:54
  • I am not sure what is your actual problem now but `request.body.asMultipartFormData.get.dataParts` will contain the Map which you have sent and if you want Json of that you can always use `Json.toJson(mapOfData)` Let me know if I got your point wrong. – Arpit Suthar Jul 05 '16 at 07:49