在Play Framework中发送文件后进行清理 [英] Cleanup after sending a file in Play Framework

查看:76
本文介绍了在Play Framework中发送文件后进行清理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ok.sendFile 从服务器下载文件

I'm using Ok.sendFile to download a file from the server.

要使其正常工作,我需要在服务器的本地文件系统中创建文件.

For this to work I need to create the file in the local file system of the server.

但是,由于服务器本身没有使用文件,并且根据用户请求创建了一个新文件,因此我想在下载操作完成后删除该文件.

However, since the server has no use for the file itself and a new file is created per user-request, I'd like to delete the file after the download operation completed.

考虑到我已经完成了操作并返回了结果,我该怎么做?

How can I do this, considering I have already completed my action and returned a Result?

 def index = Action {
    val fileToServe = generateFile("fileToServe.pdf")
    Ok.sendFile(new java.io.File(fileToServe))}
 // How can I "clean-up" fileToServe.pdf after the d/l completes?

推荐答案

我建议您使用play.api.libs.Files.TemporaryFile,以便可以使用Ok.sendFile方法的onClose自变量.

I recommend you to use play.api.libs.Files.TemporaryFile, so that you can use onClose argument of the Ok.sendFile method.

val fileToServe = TemporaryFile(new File("/tmp/" + tmpname))
Ok.sendFile(fileToServe.file, onClose = () => { fileToServe.clean })

这篇关于在Play Framework中发送文件后进行清理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆