scalafile-uploadhttp4sfs2

Scala, http4s, fs2. Why does fileupload using http4s with fs2 reads just one line while reading as bytes reads completely


I have the following snippet using multi part file uploads. One of the parts reads as byte while the other reads string. One that reads as Byte shows the correct size while the one reading as String reads only one line. What am I missing ?

  val routes = HttpRoutes.of[IO] {
    case GET -> Root                     => Ok(html.index())
    case req @ POST -> Root / "generate" =>
      req.decode[Multipart[IO]] { m =>
        m.parts.find(_.name == Some("template")) match {
          case None               => BadRequest("Missing template file")
          case Some(templatePart) => {
            val templateByteStream = for {
              byte <- templatePart.body
            } yield byte

            m.parts.find(_.name == Some("data")) match {
              case Some(datapart) =>
                val dataLineStream = for {
                  line <- datapart.body.through(utf8.decode)
                } yield line

                Ok {
                  for {
                    templateBytes <- templateByteStream.compile.toList
                    datalines     <- dataLineStream.compile.toList
                    templateSize  = templateBytes.size
                    dataLineCount = datalines.size
                  } yield s"template size $templateSize && dataline count $dataLineCount"
                }
              case None => BadRequest("Missing data file")
            }
          }
        }
      }
  }

Solution

  • Solution:

    Because you are reading the whole data as a single string, maybe you also wanted to through(text.lines)

    Credits: "Luis Miguel Mejía Suárez"