简体   繁体   中英

How to Create and test a Upload file service

I am trying my hands on with Finch. New to scala and Finch I Would to know how to create and test a file upload service. aim - to upload the file and read the contents of file

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)

}
 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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM