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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章