Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanup after sending a file in Play Framework

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?
like image 421
Barak BN Avatar asked Aug 09 '16 12:08

Barak BN


2 Answers

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 })
like image 169
Bla... Avatar answered Oct 19 '22 06:10

Bla...


In Play 2.6.x you can use below code to cleanup files:

val f = new File("/tmp/text.csv")
val name = "text.csv"
Ok.sendFile(content = f,inline = false,fileName = _ => name,
             onClose = () => f.delete)
like image 45
Manish Avatar answered Oct 19 '22 05:10

Manish