2017-10-19 91 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

相关问题