如何在使用 Play Framework 处理文件后立即删除文件

How to delete file right after processing it with Play Framework

我想用 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")
}

在后一种情况下,我无法确定流结束的时间,我将能够从文件系统中删除文件。

您可以在 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}")
        })