2

我正在尝试与 Finch 合作。Scala 和 Finch 的新手我想知道如何创建和测试文件上传服务。目标 - 上传文件并读取文件内容

import java.nio.file.{Files, Paths}
import com.twitter.util.{Await, Future}
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http.{Request, RequestBuilder, Response, Status}
import com.twitter.io.{Buf, Charsets}
import com.twitter.finagle.http.exp.Multipart.FileUpload
import io.finch._
//import io.finch.test.ServiceIntegrationSuite

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

object FinchDemO {

    //libraryDependencies ++= Seq("com.github.finagle" %% "finch-core" % "0.13.0")

    val mapper: ObjectMapper = new ObjectMapper().registerModule(DefaultScalaModule)

    //Endpoint for   http://localhost:8080/helloO
    val api: Endpoint[String] = get("helloO") {
        Ok("Hello, World!")
    } //handle { case e: ArithmeticException => BadRequest(e) }

    val upload: Endpoint[String] = post("upload" :: fileUpload("file")) {
        file: FileUpload => Ok("Success")
    }

    val server = Http.server.serve("localhost:8080", upload.toServiceAs[Text.Plain])

    Await.ready(server)

}
4

1 回答 1

0
 def fileUpload: Endpoint[IO, String] =
post("upload" :: multipartFileUploadOption("file") ) {
  (data: Option[com.twitter.finagle.http.exp.Multipart.FileUpload]) =>
    val buf= data.getOrElse(data.get.fileName, new mutable.HashMap[String, mutable.ListBuffer[FileUpload]]())
    buf match {
      case d: http.exp.Multipart.OnDiskFileUpload   => {
        val identifiers=Source.fromFile(d.content).getLines.mkString("\n")
        if(d.content.exists()){
          d.content.delete()
        }
      }
      case m: http.exp.Multipart.InMemoryFileUpload =>
        m.content match {
          case Buf.ByteArray.Owned(bytes, _, _) =>
            val f = File.createTempFile("upload", ".tmp")
            val fw = new FileOutputStream(f)
            fw.write(bytes)
            fw.close()
        }
    }
    Ok("Success")
}
于 2018-12-18T17:32:17.070 回答