playframework - 文件上传

接着上一篇的play framework 数据库连接
、作为一个web项目、文件上传是必不可少的一个功能。

使用教程

jdbc配置

upload {
  path = "/Users/lake/dounine/github/public"
  prefix = "upload/" # or ""
  allow.extension = [".jpg", ".png", ".gif"]
  domain = "http://localhost:9000/assets"
}

控制器注入使用

@Singleton
class FileController @Inject()(ws: WSClient, configuration: Configuration, @NamedDatabase("default") db: Database, cache: CacheApi, cc: ControllerComponents)(implicit assetsFinder: AssetsFinder)
  extends AbstractController(cc) {

  private val logger = org.slf4j.LoggerFactory.getLogger(classOf[FileController])
  private val uploadPath = configuration.underlying.getString("upload.path")
  private val uploadPrefix = configuration.underlying.getString("upload.prefix")
  private val allowUploadExtension = configuration.underlying.getStringList("upload.allow.extension").toArray.map(_.toString)
  private val domain = configuration.underlying.getString("upload.domain")

  def upload = Action {
    request =>
      val uploadFiles = mutable.Set[JsValueWrapper]()
      val body = request.body.asMultipartFormData
      if (body.isDefined) {
        val files = body.get.files
        files.foreach(file => {
          val fileName = file.filename
          val extension = FilenameUtils.getExtension(fileName)
          if (extension != null && allowUploadExtension.contains(s".$extension")) {
            val toFileName = s"${UUID.randomUUID().toString.replace("-", "")}.$extension"
            val postPath = s"${LocalDate.now()}/$toFileName"
            val fullPath = s"$uploadPath/$uploadPrefix$postPath"
            val accessPath = s"$domain/$uploadPrefix$postPath"
            new File(s"$uploadPath/$uploadPrefix${LocalDate.now()}").mkdirs()
            val toFile = new File(fullPath)
            file.ref.copyTo(toFile, replace = false)
            uploadFiles += Json.obj("url" -> accessPath)
          }
        })
        TimeUnit.SECONDS.sleep(1)
        Ok(Json.obj("data" -> Json.arr(uploadFiles.toSeq: _*)))
      } else {
        BadRequest
      }
  }

}

使用postman上传文件测试

访问返回的地扯

最后

play framework真的很好用、添加代码动态加载。真的很棒。
下一篇文章继续介绍在playframework中如何处理跨域CORS。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值