1
我想使用Play處理大型本地文件。 該文件在處理後應該從文件系統中刪除。這將是很容易使用SENDFILE方法是這樣的:如何在使用Play Framework處理文件後立即刪除文件
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'或'.mapMaterializedValue'在流 – cchantep