You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Provide a post() method on WS for POSTing multipart/form-data #902
A method as part of FakeRequest that is something along the lines of "fakeRequest().withMultipartFormData(formData);" would help immensely with testing controllers using multipart form data.
Based on WSClient and WSRequestHolder I implemented a multipart based request.
packagehelperimportcom.ning.http.client.{ Response=>AHCResponse, Part=>AHCPart, StringPart=>AHCStringPart, FilePart=>AHCFilePart, _ }
importplay.api.libs.ws._importplay.api.libs.ws.ning.NingWSResponseimportscala.concurrent.{ Future, Promise }
importplay.api.Play.currentimportplay.api.libs.ws.WSimportcom.ning.http.client.AsyncHttpClient._importplay.api.libs.iteratee.Enumeratorimportcollection.JavaConversions._importjava.io.Fileimportcom.ning.http.multipart.{ FilePart=>MPFilePart }
sealedtraitPart {
deftoAHCPart:AHCPart
}
caseclassStringPart(key: String, value: String) extendsPart {
deftoAHCPart= {
newAHCStringPart(key, value)
}
}
caseclassFilePart(key: String, file: File, contentType: String, charset: String) extendsPart {
deftoAHCPart= {
newMPFilePart(key, file, contentType, charset)
}
}
caseclassMultiPartWSRequestHolder(client: AsyncHttpClient, builder: AsyncHttpClient#BoundRequestBuilder, url: String) extendsWSRequestHolder {
defwithPart(part: Part):MultiPartWSRequestHolder= {
builder.addBodyPart(part.toAHCPart)
this
}
defwithParts(parts: Part*):MultiPartWSRequestHolder= {
parts.forall(p => builder.addBodyPart(p.toAHCPart) !=null)
this
}
/** * The method for this request*/valmethod:String=""/** * The body of this request*/valbody:WSBody=EmptyBody/** * 7 * The headers for this request*/valheaders:Map[String, Seq[String]] =Map()
/** * The query string for this request*/valqueryString:Map[String, Seq[String]] =Map()
/** * A calculator of the signature for this request*/valcalc:Option[WSSignatureCalculator] =None/** * The authentication this request should use*/valauth:Option[(String, String, WSAuthScheme)] =None/** * Whether this request should follow redirects*/valfollowRedirects:Option[Boolean] =None/** * The timeout for the request*/valrequestTimeout:Option[Int] =None/** * The virtual host this request will use*/valvirtualHost:Option[String] =None/** * The proxy server this request will use*/valproxyServer:Option[WSProxyServer] =None/** * sets the signature calculator for the request * @paramcalc*/defsign(calc: WSSignatureCalculator):MultiPartWSRequestHolder= {
this
}
/** * sets the authentication realm*/defwithAuth(username: String, password: String, scheme: WSAuthScheme):MultiPartWSRequestHolder= {
//not yet supportedthis
}
/** * adds any number of HTTP headers * @paramhdrs*/defwithHeaders(hdrs: (String, String)*):MultiPartWSRequestHolder= {
hdrs.forall(h => builder.setHeader(h._1, h._2) !=null)
this
}
defwithMethod(method: String):MultiPartWSRequestHolder= {
builder.setMethod(method)
this
}
/** * Sets the maximum time in milliseconds you expect the request to take. * Warning: a stream consumption will be interrupted when this time is reached.*/defwithRequestTimeout(timeout: Int):MultiPartWSRequestHolder= {
this
}
/** * Sets the virtual host to use in this request*/defwithVirtualHost(vh: String):MultiPartWSRequestHolder= {
this
}
/** * Sets the proxy server to use in this request*/defwithProxyServer(proxyServer: WSProxyServer):MultiPartWSRequestHolder= {
this
}
/** * Sets the body for this request*/defwithBody(body: WSBody):MultiPartWSRequestHolder= {
this
}
/** * adds any number of query string parameters to the*/defwithQueryString(parameters: (String, String)*):MultiPartWSRequestHolder= {
valmap= parameters.groupBy(_._1).map { case (k, v) => (k, v.map(_._2)) }
valbuilderMap=newFluentStringsMap()
map.forall { case (key, values) => builderMap.add(key, values) !=null }
builder.setQueryParameters(builderMap)
this
}
/** * Sets whether redirects (301, 302) should be followed automatically*/defwithFollowRedirects(follow: Boolean):MultiPartWSRequestHolder= {
builder.setFollowRedirects(follow)
this
}
/** * Execute this request*/defexecute():Future[WSResponse] = {
varresult=Promise[WSResponse]()
client.executeRequest(builder.build(), newAsyncCompletionHandler[AHCResponse]() {
overridedefonCompleted(response: AHCResponse) = {
result.success(NingWSResponse(response))
response
}
overridedefonThrowable(t: Throwable) = {
result.failure(t)
()
}
})
result.future
}
/** * Execute this request and stream the response body in an enumerator*/defstream():Future[(WSResponseHeaders, Enumerator[Array[Byte]])] = {
Future.failed(newRuntimeException("Not supported"))
}
}
caseclassMultPartWSClient(wsClient: WSClient) {
valclient= wsClient.underlying.asInstanceOf[AsyncHttpClient]
defurl(url: String):MultiPartWSRequestHolder= {
valbuilder= client.preparePost(url)
builder.setHeader("Content-Type", "multipart/form-data")
MultiPartWSRequestHolder(client, builder, url)
}
}
// Use the Ning AsyncHttpClient multipart class to get the bytes
val parts = Array[Part](
new StringPart("from", from),
new StringPart("to", to),
new StringPart("subject", subject),
new StringPart("text", text),
new FilePart("attachment", file)
)
val mpre = new MultipartRequestEntity(parts, new FluentCaseInsensitiveStringsMap)
val baos = new ByteArrayOutputStream
mpre.writeRequest(baos)
val bytes = baos.toByteArray
val contentType = mpre.getContentType
// Now just send the data to the WS API
client.url(endpoint)
.post(bytes)(Writeable.wBytes, ContentTypeOf(Some(contentType)))
I would have liked to be able to create implicit Writeable and ContentTypeOf instances for MultipartRequestEntity. Unfortunately however, their API is based on the assumption of one content type per typeclass instance (i.e. it would have to be the same for all MultipartRequestEntity instances).
However since it has to include the boundary value, this assumption is broken. If the typeclass could wrap an A => Option[String] rather than just an Option[String], we could just have an implicit Writeable[MultipartRequstEntity] etc.
Is there any plan to fix this? this will simplify things to a great extent (without this supported out of the box, sending a multipart request is very tedious).
Actually it would be great if somebody could help me with the PR on tests.
Actually I've left out the documentation since I'm not sure if it's good to either have something like .post(Seq(part1, part2)) and on the Java part a List. Actually maybe somebody from the core team could give me some hints.
Edit: Too bad this prolly won't go into 2.5. Actually I came too late across this.
That would be great. I actually came across this since we are sending data to another provider which uses insecure SSL, so using the underlying AhcClient takes more work than just fixing this issue..
Do you have any tip to monitor the upload progress ?
Do I have to use the underlying client to achieve that ?
I was thinking about using reactive streams to be informed periodically about the upload progress update.
Thanks !
Activity
ryanoglesby08 commentedon Apr 3, 2013
This functionality would be very helpful. Agreed.
A method as part of FakeRequest that is something along the lines of "fakeRequest().withMultipartFormData(formData);" would help immensely with testing controllers using multipart form data.
[playframework#902] Fixed bugs in enumerator streaming
[#902] Fixed bugs in enumerator streaming
joost-de-vries commentedon Jul 6, 2013
Another strong vote for this feature. I've closed the other issue #1302 in favour of this one.
ewilson commentedon Jul 9, 2014
Please consider implementing this.
ornicar commentedon Jul 31, 2014
👍
AlexGalays commentedon Jul 31, 2014
👍
cxvvs commentedon Jul 31, 2014
In the meantime, here is a workaround that was greatly inspired by some code in Play
toggm commentedon Oct 8, 2014
Based on WSClient and WSRequestHolder I implemented a multipart based request.
It can be used i..e:
It is still not fully implemented, but can be of use to anyone. Feel free to integrate that into play or use it in your own project.
nafg commentedon Dec 5, 2014
Simpler solution, based on http://stackoverflow.com/a/18723326/333643:
(I'm calling the mailgun API)
I would have liked to be able to create implicit
WriteableandContentTypeOfinstances forMultipartRequestEntity. Unfortunately however, their API is based on the assumption of one content type per typeclass instance (i.e. it would have to be the same for allMultipartRequestEntityinstances).However since it has to include the boundary value, this assumption is broken. If the typeclass could wrap an
A => Option[String]rather than just anOption[String], we could just have an implicitWriteable[MultipartRequstEntity]etc.naderghanbari commentedon Jun 3, 2015
Is there any plan to fix this? this will simplify things to a great extent (without this supported out of the box, sending a multipart request is very tedious).
cdmckay commentedon Jun 25, 2015
I wrote a Writeable to use the existing MultipartFormData object for POSTing multipart form data:
https://gist.github.com/cdmckay/4b269e9017a30111556a
And here's an example of usage:
https://gist.github.com/cdmckay/5f05cbcb5327259df1cf
So you just need to drop it in and it should work with the existing WS flow.
11 remaining items
schmitch commentedon Feb 19, 2016
Actually all the solutions here would be missing the ending, i.e:
Something like that:
--BRY7v0J3h3fIl91lUeQ6SxMJWqNHbRYi4Exp2C3s--
What would actually work is using the asyncHttpClient.preparePost().addBodyPart funtionallity i.e.:
Not sure if a Writeable has access to that. I'm looking forward to maybe add a PR.
schmitch commentedon Feb 19, 2016
Actually it would be great if somebody could help me with the PR on tests.
Actually I've left out the documentation since I'm not sure if it's good to either have something like
.post(Seq(part1, part2))and on the Java part a List. Actually maybe somebody from the core team could give me some hints.Edit: Too bad this prolly won't go into 2.5. Actually I came too late across this.
mkurz commentedon Feb 19, 2016
Maybe we can can still get this into 2.5?
gmethvin commentedon Feb 19, 2016
@mkurz At this point there should be no problem getting it into 2.5. It would only be an issue if there are major API changes.
mkurz commentedon Feb 19, 2016
@gmethvin Cool! 😄
schmitch commentedon Feb 19, 2016
That would be great. I actually came across this since we are sending data to another provider which uses insecure SSL, so using the underlying AhcClient takes more work than just fixing this issue..
david-bouyssie commentedon Feb 22, 2016
Could it be possible to have access to
onContentWriteProgresscallback or is it too complicated to interface it with the Play API ?https://asynchttpclient.github.io/async-http-client/apidocs/com/ning/http/client/AsyncCompletionHandler.html#onContentWriteProgress%28long,%20long,%20long%29
This would be a very useful feature !
Merge pull request #5698 from schmitch/added-multipart-form-data
david-bouyssie commentedon Mar 16, 2016
Do you have any tip to monitor the upload progress ?
Do I have to use the underlying client to achieve that ?
I was thinking about using reactive streams to be informed periodically about the upload progress update.
Thanks !
Fixes playframework#902 added multipart/form-data requests to play-ws
Merge pull request #5887 from mkurz/5698_backport
ilinandrii commentedon Mar 29, 2016
Is there any workaround for multipart/form-data for play 2.5?
schmitch commentedon Mar 29, 2016
it will when 2.5.1 hit @AndreyIlin
ilinandrii commentedon Mar 29, 2016
Thanks @schmitch, waiting.