如何在Web应用程序中发送文件后删除? [英] How to delete a file after sending it in a web app?
问题描述
我有一个网络应用程序。我正在使用java和spring。应用程序可以创建一个文件并将其发送到浏览器,这很好。我这样做的方式是:
I have a web application. I am using java and spring. The application can create a file and send it to the browser, this is working fine. The way I do it is:
我在Services类中创建文件,该方法将地址返回给控制器。然后控制器发送文件,并正确下载。控制器方法的代码是这样的。
I create the file in a Services class, and the method returns the address to the controller. The controller then sends the file, and it is downloaded correctly. The code for the controller method is this.
@RequestMapping("/getFile")
public @ResponseBody
FileSystemResource getFile() {
String address = Services.createFile();
response.setContentType("application/vnd.ms-excel");
return new FileSystemResource(new File (address));
}
问题是文件保存在服务器中,经过多次请求后它会有很多文件。我必须手动删除它们。问题是:如何在发送后删除此文件?或者有没有办法发送文件而不将其保存在服务器中?
The problem is that the file is saved in the server, and after many requests it will have a lot of files. I have to delete them manually. The question is: How can I delete this file after sending it? or Is there a way to send the file without saving it in the server?
推荐答案
不要使用 @ResponseBody
。让Spring注入 HttpServletResponse
并直接写入其 OutputStream
。
Don't use @ResponseBody
. Have Spring inject the HttpServletResponse
and write directly to its OutputStream
.
@RequestMapping("/getFile")
public void getFile(HttpServletResponse response) {
String address = Services.createFile();
File file = new File(address);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=" + file.getName());
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(file);
// copy from in to out
IOUtils.copy(in,out);
out.close();
in.close();
file.delete();
}
我没有添加任何异常处理。我把它留给你。
I haven't added any exception handling. I leave that to you.
FileSystemResource
实际上只是 FileInputStream <的包装器/ code> Spring使用它。
FileSystemResource
is really just is a wrapper for FileInputStream
that's used by Spring.
或者,如果你想成为硬核,你可以制作自己的 FileSystemResource
使用自己的 getOutputStream()
方法实现,该方法返回自己的 FileOutputStream
实现,删除基础文件当你打电话给 close()
时。
Or, if you want to be hardcore, you could make your own FileSystemResource
implementation with its own getOutputStream()
method that returns your own implementation of FileOutputStream
that deletes the underlying file when you call close()
on it.
这篇关于如何在Web应用程序中发送文件后删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!