Writing a test case for file uploads in Play 2.1 and Scala

后端 未结 7 1814
猫巷女王i
猫巷女王i 2021-01-02 05:39

I found the following question/answer:

Test MultipartFormData in Play 2.0 FakeRequest

But it seems things have changed in Play 2.1. I\'ve tried adapting the

7条回答
  •  别那么骄傲
    2021-01-02 06:16

    For me, the best solution for this problem is the Alex Varju one

    Here is a version updated for Play 2.5:

    object FakeMultipartUpload {
      implicit def writeableOf_multiPartFormData(implicit codec: Codec): Writeable[AnyContentAsMultipartFormData] = {
        val builder = MultipartEntityBuilder.create().setBoundary("12345678")
    
        def transform(multipart: AnyContentAsMultipartFormData): ByteString = {
          multipart.mdf.dataParts.foreach { part =>
            part._2.foreach { p2 =>
              builder.addPart(part._1, new StringBody(p2, ContentType.create("text/plain", "UTF-8")))
            }
          }
          multipart.mdf.files.foreach { file =>
            val part = new FileBody(file.ref.file, ContentType.create(file.contentType.getOrElse("application/octet-stream")), file.filename)
            builder.addPart(file.key, part)
          }
    
          val outputStream = new ByteArrayOutputStream
          builder.build.writeTo(outputStream)
          ByteString(outputStream.toByteArray)
        }
    
        new Writeable(transform, Some(builder.build.getContentType.getValue))
      }
    }
    

提交回复
热议问题