我想用 Play 处理一个大的本地文件。 该文件在处理后应立即从文件系统中删除。使用 sendFile 方法会很容易,如下所示:
def index = Action {
val fileToServe = TemporaryFile(new java.io.File("/tmp/fileToServe.pdf"))
Ok.sendFile(content = fileToServe, onClose = () => fileToServe.clean)
}
但我想以流方式处理文件以减少内存占用:
def index = Action {
val file = new java.io.File("/tmp/fileToServe.pdf")
val path: java.nio.file.Path = file.toPath
val source: Source[ByteString, _] = FileIO.fromPath(path)
Ok.sendEntity(HttpEntity.Streamed(source, Some(file.length()), Some("application/pdf")))
.withHeaders("Content-Disposition" → "attachment; filename=file.pdf")
}
在后一种情况下,我无法弄清楚流何时完成,我将能够从文件系统中删除文件。
最佳答案
您可以使用watchTermination
在Source
上,在流完成后删除文件。例如:
val source: Source[ByteString, _] =
FileIO.fromPath(path)
.watchTermination()((_, futDone) => futDone.onComplete {
case Success(_) =>
println("deleting the file")
java.nio.file.Files.delete(path)
case Failure(t) => println(s"stream failed: ${t.getMessage}")
})
关于scala - 如何在使用 Play Framework 处理文件后立即删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46830346/