我正在使用响应 << file.newInputStream 发送一个文件(类似于这个答案 here ,但我想之后删除这个文件。但是,当我在这个文件上调用 delete 时,它不会删除它。我很确定这是因为该文件仍在使用中(流式传输)。我如何检查它然后删除。
def tempfile = new File(filename)
if (tempfile) {
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "attachment;filename=${tempfile.getName()}")
response.outputStream << tempfile.newInputStream()
} else {
renderErrorMsg("ERROR: Cannot open/find file - ${filename}.")
}
tempfile.delete()
谢谢。
最佳答案
您没有关闭输入流。改变
response.outputStream << tempfile.newInputStream()
到
tempfile.withInputStream { response.outputStream << it }
后者将确保流关闭。此外,您可能希望在 finally block 中删除文件,以防引发异常。
关于java - Grails发送文件然后删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9257700/