带文件的spray-client上传表格

力拓

我有下一张表格:

   <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>

我想与name发送请求file

spray-client仅在发送文件时才能使用此功能:

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)

但是如何同时发送文件和字段呢?

拉吉什

你快到了。唯一缺少的是BodyPartPost请求中添加一些

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章