当前位置: 首页>>代码示例>>Scala>>正文


Scala FilePart类代码示例

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


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

示例1: MessageDigestController

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

import javax.inject._

import play.api.libs.streams.Accumulator
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{Action, Controller, RequestHeader}
import play.core.parsers.Multipart.{FileInfo, FilePartHandler}
import services.MessageDigestService

import scala.concurrent.{ExecutionContext, Future}


@Singleton
class MessageDigestController @Inject()(digestService: MessageDigestService)(implicit exec: ExecutionContext) extends  Controller{


  def index = Action.async {
    Future.successful( Ok(views.html.MessageDigest.index(digestService.algorithms)) )
  }

  def upload = Action(Utility.multipartFormData(digest)){ implicit  request =>
    val digest = request.body.files.map(f => (f.filename, f.ref))
    Ok(views.html.MessageDigest.digest(digest))
  }

  def digest(rh: RequestHeader): FilePartHandler[String] = {
    case FileInfo(key, fileName, contentType) =>
      val Some(Seq(algo, _*)) = rh.queryString.get("algorithm")
      Accumulator(digestService.sink(algo)).map{ d =>
       FilePart(key, fileName, contentType, d)
     }
  }
} 
开发者ID:ejosiah,项目名称:crypto-utility,代码行数:35,代码来源:MessageDigestController.scala

示例2: EncryptionController

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

import javax.inject.{Inject, Singleton}

import akka.actor.ActorSystem
import com.cryptoutility.protocol.Events.StreamingResult
import play.api.libs.streams.Accumulator
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{Action, Controller, RequestHeader}
import play.core.parsers.Multipart._
import services.EncryptionService

import scala.concurrent.{ExecutionContext, Future}
import scala.language.postfixOps

@Singleton
class EncryptionController @Inject()(encryptionService: EncryptionService)
                                    (implicit system: ActorSystem, ec: ExecutionContext) extends Controller{


  def index = Action.async {
    Future.successful( Ok(views.html.Encrypt.index() ))
  }

  def upload = Action.async(Utility.multipartFormData(digest)){ implicit  request =>
    val status: Future[StreamingResult] = request.body.files.head.ref
    status.map(s => Ok(views.html.Encrypt.status(s.wasSuccessful)))
  }

  def digest(rh: RequestHeader): FilePartHandler[Future[StreamingResult]] = {
    case FileInfo(key, fileName, contentType) =>
      val Some(clientId) = rh.session.get("userId")   // TODO fail if no clientId
      val Some(Seq(sender, _*)) = rh.queryString.get("sender")
      Accumulator(encryptionService.sink(clientId, fileName, contentType, sender)).map{ st =>
        FilePart(key, fileName, contentType, st)
      }
  }
} 
开发者ID:ejosiah,项目名称:crypto-utility,代码行数:39,代码来源:EncryptionController.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: UploadServiceSpec

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

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 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
import play.api.mvc.MultipartFormData.BadPart
import play.api.mvc.MultipartFormData.MissingFilePart
import play.api.mvc.MultipartFormData.FilePart
import play.api.libs.Files

class UploadServiceSpec extends Specification with Mockito {

  "UploadService" should {
    "uploadFile returns (File uploaded)" in new WithApplication {
      val files = Seq[FilePart[TemporaryFile]](FilePart("file", "UploadServiceSpec.scala", None, TemporaryFile("file", "spec")))
      val multipartBody = MultipartFormData(Map[String, Seq[String]](), files, Seq[BadPart](), Seq[MissingFilePart]())
      val fakeRequest = FakeRequest[MultipartFormData[Files.TemporaryFile]]("POST", "/", FakeHeaders(), multipartBody)
      val success = UploadService.uploadFile(fakeRequest)
      success must beEqualTo("File(UploadServiceSpec.scala) uploaded")
    }
    
    "uploadFile returns (Missing file)" in new WithApplication {
      val files = Seq[FilePart[TemporaryFile]]()
      val multipartBody = MultipartFormData(Map[String, Seq[String]](), files, Seq[BadPart](), Seq[MissingFilePart]())
      val fakeRequest = FakeRequest[MultipartFormData[Files.TemporaryFile]]("POST", "/", FakeHeaders(), multipartBody)
      val success = UploadService.uploadFile(fakeRequest)
      success must beEqualTo("Missing file")
    }
  }

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

示例6: ImgSaveImpl

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

import java.io.File
import java.util.UUID
import javax.inject.Inject

import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.Configuration


class ImgSaveImpl @Inject() (configuration: Configuration) extends ImgSave {
  val root = new File(configuration.getString("daos.imgSaveImpl.root").getOrElse(System.getProperty("java.io.tmpdir")))

  // make sure root dir exists
  if (!root.exists) root.mkdirs()

  override def save(productId: Long, filePart: FilePart[TemporaryFile]): Url = {
    val subdir = new File(root, productId.toString())
    val dest = new File(subdir, UUID.randomUUID() + filePart.filename)
    dest.mkdirs()
    filePart.ref.moveTo(dest, true)
    s"$productId/${dest.getName}"
  }
} 
开发者ID:kdoomsday,项目名称:doomcart,代码行数:26,代码来源:ImgSaveImpl.scala

示例7: PlaceDAO

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

import javax.inject.Inject

import com.google.common.io.Files
import models.{Place, PlaceData}
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.Files.TemporaryFile
import play.api.libs.json.Json
import play.api.mvc.Controller
import play.api.mvc.MultipartFormData.FilePart
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.commands.WriteResult
import reactivemongo.api.{Cursor, ReadPreference}
import reactivemongo.play.json.collection.JSONCollection

import scala.concurrent.{ExecutionContext, Future}

class PlaceDAO @Inject() (val reactiveMongoApi: ReactiveMongoApi)
                         (implicit ec: ExecutionContext)
    extends Controller with MongoController with ReactiveMongoComponents{
  def create(placeData: PlaceData, picture: FilePart[TemporaryFile]): Future[WriteResult] = {
    placesCollection.flatMap(_.insert(Place(placeData.name, placeData.country, placeData.description,
      Files.toByteArray(picture.ref.file))))
  }

  def all(): Future[List[Place]] = placesCollection.flatMap(_.find(Json.obj())
        .cursor[Place](ReadPreference.primaryPreferred).collect[List](Int.MaxValue, Cursor.FailOnError[List[Place]]()))

  def placesCollection: Future[JSONCollection] = database.map(_.collection[JSONCollection]("places"))
}


object PlaceDAO {
  val createPlaceForm = Form(
    mapping(
      "name" -> nonEmptyText,
      "country" -> nonEmptyText,
      "description" -> nonEmptyText
    )(PlaceData.apply)(PlaceData.unapply)
  )
} 
开发者ID:test410,项目名称:picture-gallery,代码行数:45,代码来源:PlaceDAO.scala

示例8:

//设置package包名称以及导入依赖的类
package uk.gov.homeoffice.mercury

import java.io.ByteArrayInputStream

import akka.stream.scaladsl.Source
import akka.stream.scaladsl.StreamConverters.fromInputStream
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.Scope
import org.specs2.mutable.Specification
import play.api.http.Status._
import play.api.libs.ws.WSResponse
import play.api.mvc.MultipartFormData.{DataPart, FilePart}
import uk.gov.homeoffice.mercury.boot.configuration.{HocsCredentials, HocsWebService}

import scala.concurrent.duration._


    "login and be given a login token/ticket" in new Context {
      webService endpoint "/alfresco/s/api/login" post HocsCredentials() must beLike[WSResponse] {
        case response =>
          response.status mustEqual OK
          (response.json \ "data" \ "ticket").as[String] must startWith("TICKET")
      }.awaitFor(5.seconds)
    }

    "login and be given a login token/ticket, and then submit a file" in new Context {
      webService endpoint "/alfresco/s/api/login" post HocsCredentials() flatMap { response =>
        response.status mustEqual OK
        val ticket = (response.json \ "data" \ "ticket").as[String]

        val email = fromInputStream(() => new ByteArrayInputStream("Blah blah blah blah".getBytes))
        val emailFilePart = FilePart("file", "email.txt", Some("text/plain"), email)

        webService endpoint "/alfresco/s/homeoffice/ctsv2/createCase" withQueryString ("alf_ticket" -> ticket) post Source(List(DataPart("caseType", "IMCB"), DataPart("name", "An Email"), emailFilePart))
      } must beLike[WSResponse] {
        case response =>
          println(response.json)
          println(response.statusText)
          response.status mustEqual OK
      }.awaitFor(5.seconds)
    }
  }
} 
开发者ID:UKHomeOffice,项目名称:mercury,代码行数:44,代码来源:HocsSpec.scala

示例9: 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

示例10: FormData

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

import java.io.File
import java.nio.file.attribute.PosixFilePermission._
import java.nio.file.attribute.PosixFilePermissions
import java.nio.file.{Files, Path}
import java.util
import javax.inject._

import akka.stream.IOResult
import akka.stream.scaladsl._
import akka.util.ByteString
import play.api._
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.MessagesApi
import play.api.libs.streams.{Accumulator}
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc._
import play.core.parsers.Multipart.FileInfo

import scala.concurrent.{ExecutionContext, Future}

case class FormData(name: String)



  def upload = Action(parse.multipartFormData(handleFilePartAsFile)) { implicit request =>
    val fileOption = request.body.file("name").map {
      case FilePart(key, filename, contentType, file) =>
//        logger.info(s"key = ${key}, filename = ${filename}, contentType = ${contentType}, file = $file")
        val data = operateOnTempFile(file)
        data
    }

    Ok(s"file size = ${fileOption.getOrElse("no file")}")
  }

} 
开发者ID:jdk2588,项目名称:scala-play-fileuploader,代码行数:40,代码来源:UploadController.scala


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