问题
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:
- absolute path of the deployed Play! application
- base (relative) path to assets folder
- /images
- 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