2017-10-19 89 views
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") 
} 

而在後一種情況下,我無法弄清楚流完成的時刻,我可以從文件系統中刪除文件。

+1

使用'.watchTermination'或'.mapMaterializedValue'在流 – cchantep

回答

1

您可以在Source上使用watchTermination在流完成後刪除文件。例如:

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}") 
     }) 
+0

偉大的作品,謝謝! – vicont

相關問題