PlayWS发布多部分表单数据

时间:2016-07-06 13:54:10

标签: scala playframework akka-stream

我正在尝试使用PlayWS将文件和一些数据发布到Mailgun但我收到此错误:

Cannot write an instance of akka.stream.scaladsl.Source[play.api.mvc.MultipartFormData.Part[akka.stream.scaladsl.Source[akka.util.ByteString, Any]], Any] to HTTP response. Try to define a Writeable[akka.stream.scaladsl.Source[play.api.mvc.MultipartFormData.Part[akka.stream.scaladsl.Source[akka.util.ByteString, Any]], Any]]

代码如下所示:

def ws(url: String) = 
  wsClient.url(s"${url}").withAuth("api", apiKey, WSAuthScheme.BASIC)

ws(url).post(Source(
  FilePart("test", "test.txt", Option("text/plain"), FileIO.fromFile(file)) :: 
  DataPart("key", "value") :: 
  List()))

我知道错误要求我做什么,但在这种情况下我不知道如何为Writable实施Source。这不应该有预定义的实现吗?

2 个答案:

答案 0 :(得分:1)

已实施,但仅限于2.5.1 +

答案 1 :(得分:1)

AFAIK,仅从Play 2.6.x (具体为here, play-ws)开始实施。

Play 2.5.x虽然有变通办法!

As documented here

  • 要流式传输Source,您需要将其封在StreamBodyas in内:

val wsResponse: Future[WSResponse] = ws.url(url) .withBody(StreamedBody(largeImageFromDB)).execute("PUT")

ws.url(url).post(Source(FilePart("hello", "hello.txt", Option("text/plain"), FileIO.fromFile(tmpFile)) :: DataPart("key", "value") :: List()))