• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala MultipartFormData类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中play.api.mvc.MultipartFormData的典型用法代码示例。如果您正苦于以下问题:Scala MultipartFormData类的具体用法?Scala MultipartFormData怎么用?Scala MultipartFormData使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了MultipartFormData类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: UploadZipRecipeForm

//设置package包名称以及导入依赖的类
package requests

import models.Password
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import play.api.libs.Files
import play.api.mvc.{MultipartFormData, Request}

case class UploadZipRecipeForm(
    version: String,
    password: String,
    file: MultipartFormData.FilePart[Files.TemporaryFile]
) {
  def passwordRecord = {
    Password(0L, version, MyBCrypt.createHash(password))
  }
}

object UploadZipRecipeForm {
  def fromReq(req: Request[MultipartFormData[Files.TemporaryFile]]): Option[UploadZipRecipeForm] = {
    val data = req.body.dataParts
    for {
      version <- data.get("ver").flatMap(_.headOption)
      password <- data.get("password").flatMap(_.headOption)
      file <- req.body.file("zipFile")
    } yield new UploadZipRecipeForm(version, password, file)
  }
}

object MyBCrypt {
  val bcrypt = new BCryptPasswordEncoder(12)
  def createHash(password: String) = bcrypt.encode(password)
  def authenticate(password: String, hash: String): Boolean =
    bcrypt.matches(password, hash)
} 
开发者ID:ponkotuy,项目名称:FactorioRecipe,代码行数:35,代码来源:UploadZipRecipeForm.scala


示例2: Utility

//设置package包名称以及导入依赖的类
package controllers

import play.api.Play
import play.api.mvc.{BodyParser, MultipartFormData, RequestHeader}
import play.core.parsers.Multipart


object Utility {

  import play.api.mvc.BodyParsers.parse._


  def multipartFormData[A](filePartHandler: RequestHeader => Multipart.FilePartHandler[A], maxLength: Long = DefaultMaxDiskLength): BodyParser[MultipartFormData[A]] = {
    BodyParser("multipartFormData") { request =>
      val app = play.api.Play.current // throw exception
    implicit val mat = app.materializer
      val bodyAccumulator = Multipart.multipartParser(DefaultMaxTextLength, filePartHandler(request)).apply(request)
     // TODO enforceMaxLength(request, maxLength, bodyAccumulator) or maybe not
      bodyAccumulator
    }
  }
} 
开发者ID:ejosiah,项目名称:crypto-utility,代码行数:23,代码来源:Utility.scala


示例3: MultipartFormDataWritable

//设置package包名称以及导入依赖的类
package helpers

import java.nio.file.{Files, Paths}

import play.api.http.{HeaderNames, Writeable}
import play.api.libs.Files.TemporaryFile
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{AnyContentAsMultipartFormData, Codec, MultipartFormData}

//Check -> http://tech.fongmun.com/post/125479939452/test-multipartformdata-in-play

object MultipartFormDataWritable {
  val boundary = "--------ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

  def formatDataParts(data: Map[String, Seq[String]]) = {
    val dataParts = data.flatMap {
      case (key, values) =>
        values.map { value =>
          val name = s""""$key""""
          s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name\r\n\r\n$value\r\n"
        }
    }.mkString("")
    Codec.utf_8.encode(dataParts)
  }

  def filePartHeader(file: FilePart[TemporaryFile]) = {
    val name = s""""${file.key}""""
    val filename = s""""${file.filename}""""
    val contentType = file.contentType.map { ct =>
      s"${HeaderNames.CONTENT_TYPE}: $ct\r\n"
    }.getOrElse("")
    Codec.utf_8.encode(s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filename\r\n$contentType\r\n")
  }

  val singleton = Writeable[MultipartFormData[TemporaryFile]](
    transform = { form: MultipartFormData[TemporaryFile] =>
    formatDataParts(form.dataParts) ++
      form.files.flatMap { file =>
        val fileBytes = Files.readAllBytes(Paths.get(file.ref.file.getAbsolutePath))
        filePartHeader(file) ++ fileBytes ++ Codec.utf_8.encode("\r\n")
      } ++
      Codec.utf_8.encode(s"--$boundary--")
  },
    contentType = Some(s"multipart/form-data; boundary=$boundary")
  )

  implicit val anyContentAsMultipartFormWritable: Writeable[AnyContentAsMultipartFormData] = {
    MultipartFormDataWritable.singleton.map(_.mdf)
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:52,代码来源:MultiPartFormDataWritable.scala


示例4: MultipartFormDataWritable

//设置package包名称以及导入依赖的类
package de.zalando.play.controllers

import java.nio.file.{ Files, Paths }

import akka.util.ByteString
import play.api.http.{ HeaderNames, Writeable }
import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{ Codec, MultipartFormData }


object MultipartFormDataWritable {

  val boundary = "--------ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

  def formatDataParts(data: Map[String, Seq[String]]): ByteString = {
    val dataParts = data.flatMap {
      case (key, values) =>
        values.map { value =>
          val name = s""""$key""""
          s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name\r\n\r\n$value\r\n"
        }
    }.mkString("")
    val bytes: ByteString = Codec.utf_8.encode(dataParts)
    bytes
  }

  def filePartHeader(file: FilePart[TemporaryFile]): ByteString = {
    val name = s""""${file.key}""""
    val filename = s""""${file.filename}""""
    val contentType = file.contentType.map { ct =>
      s"${HeaderNames.CONTENT_TYPE}: $ct\r\n"
    }.getOrElse("")
    Codec.utf_8.encode(s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filename\r\n$contentType\r\n")
  }

  val singleton = Writeable[MultipartFormData[TemporaryFile]](
    transform = { form: MultipartFormData[TemporaryFile] =>
    formatDataParts(form.dataParts) ++
      form.files.flatMap { file =>
        val fileBytes = Files.readAllBytes(Paths.get(file.ref.file.getAbsolutePath))
        filePartHeader(file) ++ fileBytes ++ Codec.utf_8.encode("\r\n")
      } ++
      Codec.utf_8.encode(s"--$boundary--")
  },
    contentType = Some(s"multipart/form-data; boundary=$boundary")
  )
} 
开发者ID:LappleApple,项目名称:api-first-hand,代码行数:49,代码来源:MultipartFormDataWritable.scala


示例5: ExtractFile

//设置package包名称以及导入依赖的类
package models

import java.io.File

import com.github.pochi.runner.scripts.{ScriptRunner, ScriptRunnerBuilder}
import play.api.libs.Files
import play.api.mvc.{MultipartFormData, Request}
import services.Extracter

class ExtractFile(request: Request[MultipartFormData[Files.TemporaryFile]], kindOfBirthmark: Birthmark) {
  val result = request.body.file("file").map { file =>
    val filename = file.filename
    val contentType = file.contentType
    file.ref.moveTo(new File("files", filename))

    // filename, kindOfBirthmark
//    new Extracter().getExtractFile("files/" + file.filename, kindOfBirthmark.birthmark)
    def getExtractFile: String ={
      val builder: ScriptRunnerBuilder = new ScriptRunnerBuilder
      val runner: ScriptRunner = builder.build
      val arg: Array[String] = Array("./extract.js", "files/" + file.filename, kindOfBirthmark.birthmark)
      runner.runsScript(arg)
      file.filename + ".csv"
    }
    getExtractFile
  }
  val extractFile = result.get
  println(result.get)
} 
开发者ID:mitubaEX,项目名称:InMITU,代码行数:30,代码来源:ExtractFile.scala


示例6: ExtractFile

//设置package包名称以及导入依赖的类
package models

import java.io.File

import com.github.pochi.runner.scripts.{ScriptRunner, ScriptRunnerBuilder}
import play.api.libs.Files
import play.api.mvc.{MultipartFormData, Request}
import services.Extracter

class ExtractFile(request: Request[MultipartFormData[Files.TemporaryFile]], kindOfBirthmark: Birthmark) {
  val result = request.body.file("file").map { file =>
    val filename = file.filename
    val contentType = file.contentType
    file.ref.moveTo(new File("files", filename))

    // filename, kindOfBirthmark
//    new Extracter().getExtractFile("files/" + file.filename, kindOfBirthmark.birthmark)
    def getExtractFile: String ={
      val builder: ScriptRunnerBuilder = new ScriptRunnerBuilder
      val runner: ScriptRunner = builder.build
      val arg: Array[String] = Array("./extract.js", "files/" + file.filename, kindOfBirthmark.birthmark)
      runner.runsScript(arg)
      file.filename + ".csv"
    }
    getExtractFile
  }
  val extractFile = result.get
} 
开发者ID:mitubaEX,项目名称:MITUBASearcher,代码行数:29,代码来源:ExtractFile.scala


示例7: FacebookC

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.{Inject, Singleton}

import play.api.Environment
import play.api.cache.CacheApi
import play.api.db.slick.DatabaseConfigProvider
import play.api.i18n.MessagesApi
import play.api.libs.Files
import play.api.mvc.{Action, MultipartFormData, Request}
import services.FacebookService

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


@Singleton
class FacebookC @Inject()(dbConfigProvider: DatabaseConfigProvider, env: Environment, cache: CacheApi, messagesApi: MessagesApi)
  extends FacebookService(dbConfigProvider, env, cache, messagesApi) {


  def auth = Action.async { implicit req: Request[_] =>
    Future successful Redirect(AUTH_URL(req, env))
  }

  def callback(code: String) = Action.async { implicit req: Request[_] =>
    super.callback(code).flatMap {
      case None => Future successful Redirect(routes.LoginC.login().url)
      case Some(account) => Future successful Redirect(routes.MyPageC.index().url).withSession(account.session)
    }
  }

  def remove = Action.async { implicit req: Request[_] =>
    removeToken.flatMap {
      case false => Future successful Redirect(routes.LoginC.login().url)
      case true => Future successful Redirect(routes.MyPageC.index().url)
    }
  }

  def post: Action[MultipartFormData[Files.TemporaryFile]] = Action.async(parse.multipartFormData) { implicit req: Request[_] =>
    postMessage.flatMap {
      case Right(bool) =>
        if (bool) Future successful Redirect(routes.SplashC.index().url)
        else Future successful Redirect(routes.LoginC.login().url)
      case Left(_) => Future successful Redirect(routes.FacebookC.auth().url)
    }
  }

} 
开发者ID:yukihirai0505,项目名称:sns-alert,代码行数:50,代码来源:FacebookC.scala


示例8: UploadService

//设置package包名称以及导入依赖的类
package services

import java.io.File
import play.api.Logger
import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData
import play.api.mvc.Request
import java.util.UUID
import play.api.Play
import play.api.Play.current
import utils.S3Utility

object UploadService extends UploadService {
  val s3Utility: S3Utility = S3Utility
}

trait UploadService {

  private val log: Logger = Logger(this.getClass)

  val s3Utility: S3Utility

  
  def uploadFile(request: Request[MultipartFormData[TemporaryFile]]): String = {
    log.error("Called uploadFile function" + request)
    request.body.file("file").map { file =>
      import java.io.File
      val filename = file.filename
      val contentType = file.contentType
      log.error(s"File name : $filename, content type : $contentType")
      val uniqueFile = new File(s"/tmp/${UUID.randomUUID}_$filename")
      file.ref.moveTo(uniqueFile, true)
      if (Play.isProd) {
        try {
          val bucket = s3Utility.getBucketByName("test").getOrElse(s3Utility.createBucket("test"))
          val result = s3Utility.createObject(bucket, filename, uniqueFile)
          s"File uploaded on S3 with Key : ${result.key}"
        } catch {
          case t: Throwable => log.error(t.getMessage, t); t.getMessage
        }
      } else {
        s"File(${filename}) uploaded"
      }
    }.getOrElse {
      "Missing file"
    }
  }

} 
开发者ID:boris9999,项目名称:scala-aws,代码行数:50,代码来源:UploadService.scala


示例9: ApplicationSpec

//设置package包名称以及导入依赖的类
import scala.concurrent.Future
import org.specs2.mock.Mockito
import org.specs2.mutable._
import org.specs2.runner._
import controllers.Application
import play.api.mvc.Controller
import play.api.mvc.Results
import play.api.test._
import play.api.test.Helpers._
import services.UploadService
import org.junit.runner.RunWith
import play.api.mvc.Result
import play.api.mvc.Request
import play.api.mvc.MultipartFormData
import play.api.libs.Files.TemporaryFile


@RunWith(classOf[JUnitRunner])
class ApplicationSpec extends Specification with Mockito with Results {

  val mockedUploadService: UploadService = mock[UploadService]

  object TestController extends Controller with Application {
    val uploadService: UploadService = mockedUploadService
  }

  "Application" should {

    "send 404 on a bad request" in new WithApplication {
      route(FakeRequest(GET, "/boum")) must beNone
    }

    "render the index page" in new WithApplication {
      val home = route(FakeRequest(GET, "/")).get

      status(home) must equalTo(OK)
      contentType(home) must beSome.which(_ == "text/html")
      contentAsString(home) must contain("Welcome to Play")
    }

    "should be valid" in new WithApplication {
      val request = mock[Request[MultipartFormData[TemporaryFile]]]
      mockedUploadService.uploadFile(request) returns "File Uploaded"
      val result: Future[Result] = TestController.upload().apply(request)
      status(result) must equalTo(SEE_OTHER)
    }
  }
} 
开发者ID:boris9999,项目名称:scala-aws,代码行数:49,代码来源:ApplicationSpec.scala


示例10: WiredApiService

//设置package包名称以及导入依赖的类
package services

import java.time.OffsetDateTime

import play.api.libs.Files
import play.api.mvc.MultipartFormData
import shared.models.WiredApiModel.ApiResult
import shared.models.slick.default._
import shared.services.WiredApi
import shared.utils.Implicits
import shared.utils.LoremIpsum

class WiredApiService(user: User,
                      services: Services,
                      files: Seq[MultipartFormData.FilePart[Files.TemporaryFile]])
    extends WiredApi
    with Implicits {

  override def ping(): ApiResult[String] = "pong".asResult

  override def now(): ApiResult[OffsetDateTime] = OffsetDateTime.now.asResult

  override def createLoremIpsum(): ApiResult[List[String]] = {
    Thread.sleep(2000)
    LoremIpsum.paragraphs(15).asResult
  }
} 
开发者ID:Daxten,项目名称:bay-scalajs.g8,代码行数:28,代码来源:WiredApiService.scala


示例11: fop

//设置package包名称以及导入依赖的类
package bmlogic.common.files

import java.io.File

import play.api.libs.Files
import java.io.FileInputStream

import bmutil.errorcode.ErrorCode
import play.api.mvc.MultipartFormData
import play.api.libs.Files.TemporaryFile
import play.api.libs.json.Json
import play.api.libs.json.Json._
import play.api.libs.json.JsValue

object fop {
	def uploadFile(data : MultipartFormData[TemporaryFile]) : JsValue = {
	  	data.file("upload").map { x =>
            Files.TemporaryFile(x.ref.file).moveTo(new File("upload/" + x.filename), true)

			Json.toJson(Map("status" -> toJson("ok"),
                            "file_name" -> toJson(x.filename),
                            "result" -> toJson("success")))
	  	  	
	  	}.getOrElse {
			ErrorCode.errorToJson("post image error")
	  	} 
	}

	def downloadFile(name : String) : Array[Byte] = {
	  	val file = new File("upload/" + name)
		val reVal : Array[Byte] = new Array[Byte](file.length.intValue)
		new FileInputStream(file).read(reVal)
		reVal
	}
} 
开发者ID:AlfredYang1986,项目名称:Dongda-Service,代码行数:36,代码来源:fop.scala


示例12: getFile

//设置package包名称以及导入依赖的类
package parsers

import io.circe.Decoder
import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.Results.BadRequest
import play.api.mvc.{MultipartFormData, Result}
import io.circe.generic.auto._

trait FormDataUtil extends JsonUtils {

  def getFile(key: String, parsedBody: MultipartFormData[TemporaryFile]): Either[Result, FilePart[TemporaryFile]] = {
    parsedBody.file(key) match {
      case Some(file) => Right(file)
      case None => Left(BadRequest(s"""{"cause":"File part "$key" is missing from the form data"}"""))
    }
  }

  def getMultipleData(key: String, parsedBody: MultipartFormData[TemporaryFile]): Either[Result, Seq[String]] = {
    parsedBody.dataParts.get(key) match {
      case Some(data) => Right(data)
      case None => Left(BadRequest(s"""{"cause":"Field "$key" is missing from the form data"}"""))
    }
  }

  def getOptionalMultipleData(key: String, parsedBody: MultipartFormData[TemporaryFile]): Either[Result, Seq[String]] = {
    parsedBody.dataParts.get(key) match {
      case Some(data) => Right(data)
      case None => Right(Seq())
    }
  }

  def getMultipleParsedData[T](key: String, parsedBody: MultipartFormData[TemporaryFile])(implicit reader: Decoder[T]): Either[Result, Seq[T]] =
    getMultipleData(key, parsedBody).right.flatMap {
      fields =>
        fields.map(parseJson[T](_)).foldRight(Right(Nil): Either[Result, List[T]]) {
          (result, acc) =>
            for (
              result <- result.right;
              acc <- acc.right
            ) yield result :: acc
        }
    }

  def getData(key: String, parsedBody: MultipartFormData[TemporaryFile]): Either[Result, String] = getMultipleData(key, parsedBody) match {
    case Left(e) => Left(e)
    case Right(seq) =>
      val size = seq.size
      if (size != 1)
        Left(BadRequest(s"""{"cause":"Expected one value for "$key", got $size"}"""))
      else
        Right(seq.head)
  }

  def getParsedData[T](key: String, parsedBody: MultipartFormData[TemporaryFile])(implicit reader: Decoder[T]): Either[Result, T] =
    getData(key, parsedBody).right.flatMap {
      str =>
        parseJson[T](str)
    }
} 
开发者ID:digitalinteraction,项目名称:intake24,代码行数:61,代码来源:FormDataUtil.scala


示例13: TokenCheckServiceImpl

//设置package包名称以及导入依赖的类
package services.security.Impl

import conf.util.Events
import domain.security.{LogInStatus, TokenFailException}
import play.api.libs.json.JsValue
import play.api.mvc.{AnyContent, MultipartFormData, Request}
import services.security.{ManageTokenService, TokenCheckService}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.reflect.io.File


class TokenCheckServiceImpl extends TokenCheckService{

  override def getTokenForUpload(request: Request[MultipartFormData[File]]): Future[LogInStatus] = {

    getTokenValue(
      request.headers.get("Authorization").getOrElse(""),
      request.headers.get("User-Agent").getOrElse(""))
  }

  override def getTokenfromParam(request: Request[AnyContent]): Future[LogInStatus] = {
    getTokenValue(
      request.headers.get("Authorization").getOrElse(""),
      request.headers.get("User-Agent").getOrElse(""))
  }

  override def getToken(request: Request[JsValue]): Future[LogInStatus] = {
    getTokenValue(
      request.headers.get("Authorization").getOrElse(""),
      request.headers.get("User-Agent").getOrElse(""))
  }

  override def getTokenValue(token: String, agent:String): Future[LogInStatus] = {
    ManageTokenService.apply.isTokenValid(token,agent) map ( isValid =>{
      if(isValid) LogInStatus(Events.TOKENVALID) else throw TokenFailException("Error")
    })
  }

} 
开发者ID:boniface,项目名称:infoshareapi,代码行数:42,代码来源:TokenCheckServiceImpl.scala



注:本文中的play.api.mvc.MultipartFormData类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala PendingIntent类代码示例发布时间:2022-05-23
下一篇:
Scala Platform类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap