我想使用 Spray 将多部分表单发布到服务器。特别是我想发布一张图片。
我遇到的问题是将文件编组为多部分。尽管在 Spray 他们提到它是一个默认的 Marshaller,但我似乎无法将两者结合在一起。
我目前使用的是 Spray 1.0-M7,因为我还没有迁移到 Scala 2.10,如果该示例可以与该分支兼容,那就太好了。
我目前拥有的是这样的:
val bis = new BufferedInputStream(new FileInputStream(file))
val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray
Logger.error("About to post with spray")
pipeline(Post("/saveImageWithSpray", bArray))
当然,我收到一条错误消息:
For request 'POST /saveImageWithSpray' [Missing boundary header]
我发现的大多数示例都使用 content(as[X]) 指令来编组,但我没有使用 Spray-routing,我只需要在基于另一个框架的应用程序中使用 spray-client 执行帖子。
谢谢
编辑
我实际上已经设法像这样编组它:
val pipeline = (
addHeader("Content-Type", "multipart/form-data")
~> sendReceive(conduit)
)
val bis = new BufferedInputStream(new FileInputStream(file, "UTF-8"))
val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray
Logger.error("About to post with spray "+bArray.length.toString)
pipeline(Post("/saveImageWithSpray", MultipartFormData(Map(
"spray-file" -> BodyPart(
HttpEntity(Some(HttpBody(ContentType(MediaTypes.`image/gif`), bArray))),
HttpHeaders.`Content-Disposition`("form-data", Map("name" -> "spray-file","filename"->"Fuurin (Glass Wind Chime).gif"))::Nil
)
))))
不幸的是,这仍然不起作用,数据正在传输,但服务器找不到文件。
一个wireshark捕获揭示了以下内容:
POST /saveImageWithSpray HTTP/1.1
Host: localhost:9000
User-Agent: spray-can/1.0-M7
Content-Type: multipart/form-data; boundary="oxz40rxXXQyDx+IUKcz7QYpJ"
Content-Length: 1725
--oxz40rxXXQyDx+IUKcz7QYpJ
Content-Disposition: form-data; name="spray-file"
Content-Disposition: form-data; name="spray-file"; filename="Fuurin (Glass Wind Chime).gif"
Content-Type: image/gif
GIF89a0.0..........
BINARY DATA
..P...L0..8.....X.....l..?...;
--oxz40rxXXQyDx+IUKcz7QYpJ--HTTP/1.1 500 Internal Server Error
Content-Type: text/plain; charset=utf-8
Content-Length: 25
File not found spray-file
这是使用 Advanced Rest Client 发出的有效请求的捕获:
POST /saveImageWithSpray HTTP/1.1
Host: localhost:9000
Connection: keep-alive
Content-Length: 2573
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryuiIgwVg3rBQLFNGB
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
------WebKitFormBoundaryuiIgwVg3rBQLFNGB
Content-Disposition: form-data; name="spray-file"; filename="Gunsen (Fan) .gif"
Content-Type: image/gif
GIF89a0.0.........u.QQ..Z..z.wW[[[.
BINARY DATA
.....&...Z(.c.Q.....T.B7..S...!...p[...8."...;
------WebKitFormBoundaryuiIgwVg3rBQLFNGB--
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 24
File uploaded with spray