4

I have a next form:

   <form action="/upload" method="POST" enctype="multipart/form-data">
        <input type="text" name="name">
        <input type="file" name="file">
        <input type="submit" value="Upload image">
    </form>

I want to send request with name and with file

I use spray-client for this, when i send only file this work fine:

val file = "my-image.png"
val bis = new BufferedInputStream(new FileInputStream(file))
val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray

val url = "http://example.com/upload"

val httpData = HttpData(bArray)
val httpEntity = HttpEntity(ContentTypes.`image/png`, httpData).asInstanceOf[HttpEntity.NonEmpty]
val formFile = FormFile("my-image", httpEntity)
val bodyPart = BodyPart(formFile, "my-image")
val req = Post(url, MultipartFormData(Map("spray-file" -> bodyPart)))

val pipeline = (addHeader("Content-Type", "multipart/form-data")
  ~> sendReceive
)

pipeline(req)

But how to send at the same time file and fields?

Rajish
  • 6,755
  • 4
  • 34
  • 51
lito
  • 989
  • 8
  • 21
  • 1
    Can be helpful: https://github.com/spray/spray/blob/269ce885d3412e555237bb328aae89457f57c660/spray-httpx/src/test/scala/spray/httpx/FormFieldSpec.scala#L31 – sap1ens May 09 '15 at 20:29
  • Possible duplicate of [How can I process a file uploaded through an HTML form in Spray/Scala/Java?](http://stackoverflow.com/questions/7503307/how-can-i-process-a-file-uploaded-through-an-html-form-in-spray-scala-java) – maya.js Mar 09 '16 at 15:01

1 Answers1

3

You're almost there. The only thing that's missing is adding some BodyParts to the Post request:

def headers(params: (String, String)*) =
  Seq(HttpHeaders.`Content-Disposition`("form-data", Map(params: _*)))

val api_key = "abcdef123456"
val api_secret = "a42ecd098a5389=="

val formData = MultipartFormData(Seq(
  BodyPart(api_key, headers("name" -> "api_key")),
  BodyPart(api_secret, headers("name" -> "api_secret")),
  BodyPart(formFile, "img")
))

val req = Post(url, formData)
Rajish
  • 6,755
  • 4
  • 34
  • 51
  • I give up. What are "api_key" and "api_secret", given that they're not referenced elsewhere ? – Brian Agnew Mar 15 '16 at 18:43
  • Ah. Got it. "api_key" is the parameter name, and you provide the *value* as the first argument to BodyPart. Perhaps you could amend for clarification ? Or should I have understood that ? – Brian Agnew Mar 16 '16 at 12:59
  • To be clear, the above answer *is* useful, nonetheless. Thanks – Brian Agnew Mar 16 '16 at 12:59