Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I managed to get this working with Play 2.1 based on various mailing list suggestions. Here's how I do it:</p> <pre><code>import scala.language.implicitConversions import java.io.{ ByteArrayOutputStream, File } import org.apache.http.entity.mime.MultipartEntity import org.apache.http.entity.mime.content.{ ContentBody, FileBody } import org.specs2.mutable.Specification import play.api.http.Writeable import play.api.test.{ FakeApplication, FakeRequest } import play.api.test.Helpers._ trait FakeMultipartUpload { case class WrappedFakeRequest[A](fr: FakeRequest[A]) { def withMultipart(parts: (String, ContentBody)*) = { // create a multipart form val entity = new MultipartEntity() parts.foreach { part =&gt; entity.addPart(part._1, part._2) } // serialize the form val outputStream = new ByteArrayOutputStream entity.writeTo(outputStream) val bytes = outputStream.toByteArray // inject the form into our request val headerContentType = entity.getContentType.getValue fr.withBody(bytes).withHeaders(CONTENT_TYPE -&gt; headerContentType) } def withFileUpload(fileParam: String, file: File, contentType: String) = { withMultipart(fileParam -&gt; new FileBody(file, contentType)) } } implicit def toWrappedFakeRequest[A](fr: FakeRequest[A]) = WrappedFakeRequest(fr) // override Play's equivalent Writeable so that the content-type header from the FakeRequest is used instead of application/octet-stream implicit val wBytes: Writeable[Array[Byte]] = Writeable(identity, None) } class MyTest extends Specification with FakeMultipartUpload { "uploading" should { "be easier than this" in { running(FakeApplication()) { val uploadFile = new File("/tmp/file.txt") val req = FakeRequest(POST, "/upload/path"). withFileUpload("image", uploadFile, "image/gif") val response = route(req).get status(response) must equalTo(OK) } } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload