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

Scala TemporaryFile类代码示例

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

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



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

示例1: Application

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

import java.io.File

import play.api.Logger
import play.api.libs.Files.TemporaryFile
import play.api.mvc._
import play.api.libs.json.Json._

class Application extends Controller {
  private val log: Logger = Logger(this.getClass)

  def index = Action(implicit request => Ok(views.html.index(Utils.getListOfFiles("./dataStore"))))

  def main = Action(implicit request => Ok(views.html.main("Title")(play.twirl.api.Html("Content"))))

  def report = Action(implicit request => Ok(views.html.report()))

  def doUpload(request: Request[MultipartFormData[TemporaryFile]]): Result = {
    request.body.file("file").map { file =>
      val filename = file.filename
      val contentType = file.contentType.get
      val prefix = System.currentTimeMillis().toString.substring(4)
      file.ref.moveTo(new File(s"./dataStore/($prefix)$filename"))
      log.info(s"$filename : $contentType")
      Ok("File has been uploaded")
    }.getOrElse {
      log.error("Upload failed!")
      Redirect(routes.Application.index)
      InternalServerError("File has NOT been uploaded")
    }
  }

  def uploadFile = Action(parse.multipartFormData) { request =>
    doUpload(request)
  }

  def test = Action(implicit request => Ok(currentApi))

  private def currentApi(implicit request: RequestHeader) = toJson(
    Map[String,String](
        "host" -> (request.host+"."+request.domain),
        "uri"-> request.uri,
        "session"->request.session.toString))
} 
开发者ID:olka,项目名称:test-reports-agregator,代码行数:46,代码来源:Application.scala


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


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


示例4: ImageHelper

//设置package包名称以及导入依赖的类
package utils.images

import java.io.File
import javax.imageio.ImageIO

import com.google.inject.Inject
import com.sksamuel.scrimage.Image
import com.sksamuel.scrimage.nio.JpegWriter
import play.api.libs.Files.TemporaryFile

import scala.concurrent.Future


class ImageHelper @Inject() (configuration: play.api.Configuration) {
  import play.api.libs.concurrent.Execution.Implicits.defaultContext
  def getImageDimensions(imageFile: File): Future[(Int, Int)] = Future[(Int, Int)] {
    val image = ImageIO.read(imageFile)
    (image.getHeight, image.getWidth)
  }
  lazy val maxWidth = configuration.underlying.getInt("octotagger.images.thumbnail.maxWidth")
  lazy val maxHeight = configuration.underlying.getInt("octotagger.images.thumbnail.maxHeight")
  def createThumbnail(image: Image): Future[TemporaryFile] = Future[TemporaryFile] {
    implicit val writer = JpegWriter().withCompression(50).withProgressive(true)
    val file = File.createTempFile("thumbnails", ".jpg")
    image.max(maxWidth, maxHeight).output(file)
    new TemporaryFile(file)
  }
  def convertImageToJpeg(image: Image): Future[TemporaryFile] = Future[TemporaryFile] {
    implicit val writer = JpegWriter().withCompression(30).withProgressive(true)
    val file = File.createTempFile("converted", ".jpg")
    image.output(file)
    new TemporaryFile(file)
  }

} 
开发者ID:SwaggerTagger,项目名称:octo-tagger-backend,代码行数:36,代码来源:ImageHelper.scala


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


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


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


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


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


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala toJson类代码示例发布时间:2022-05-23
下一篇:
Scala Jedis类代码示例发布时间: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