Play framework - how to write to public assets

有些话、适合烂在心里 提交于 2019-12-24 07:39:47

问题


Trying to process uploaded images and then display the result. Was following: https://github.com/playframework/play-scala-fileupload-example

Relevant snippet:

private def handleFilePartAsFile: FilePartHandler[File] = {
  case FileInfo(partName, filename, contentType) =>
    val path: Path = Files.createTempFile("multipartBody", "tempFile")
    val fileSink: Sink[ByteString, Future[IOResult]] = FileIO.toPath(path)
    val accumulator: Accumulator[ByteString, IOResult] = Accumulator(fileSink)
    accumulator.map {
      case IOResult(count, status) =>
        logger.info(s"count = $count, status = $status")
        FilePart(partName, filename, contentType, path.toFile)
    }
}

How can I get the absolute path of the /public/images asset folder, to write the image to, instead of using Files.createTempFile?


回答1:


I suppose you will use Play 2.6 like in the project from the link you mentioned. In that case you can construct path to file in /public/images folder from 4 paths:

  1. absolute path of the deployed Play! application
  2. base (relative) path to assets folder
  3. /images
  4. file name

In Scala:

val path = env.rootPath + af.assetsBasePath + "/images/" + filename

For 1st and 2nd parts you need to auto-inject Environment and AssetsFinder objects like:

@Singleton
class HomeController @Inject() (cc:MessagesControllerComponents, 
    af: AssetsFinder, env: Environment)
(implicit executionContext: ExecutionContext)
...


来源:https://stackoverflow.com/questions/47775060/play-framework-how-to-write-to-public-assets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!