play framework 文件上传

接着上一篇的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 文件上传_第1张图片

访问返回的地扯

play framework 文件上传_第2张图片

最后

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

你可能感兴趣的:(play framework 文件上传)