I have an upload servlet that is working great but leaves it's temporary files lying around. I am trying to use the part.delete() to clean them up as I go, but they are not deleting.
The docs say the container will delete them when it does GC. But even if I wait an hour and eventually shut the server down, they are still there...
What's the trick? It's Eclipse Kepler with Tomcat 7.0.47 on Windows for the moment. But production will be Linux.
Thanks
Code condensed substantially:
@MultipartConfig(location = "C:/tmp",
fileSizeThreshold=1024*1024*10, // 10MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50) // 50MB
@WebServlet("/upload.do")
...
for (Part part : request.getParts()) {
String filename = getFilename(part);
if(!(filename==null)){
part.write("/elsewhere/"+filename);
part.delete();
} else {
out.println("skip field...");
}
}
Hi you can create Servlet Listner like this
@WebListener
public class ContextListner implements ServletRequestListener, ServletContextListener {
public ContextListner() {
}
public void requestDestroyed(ServletRequestEvent sre) {
deleteDir(sre.getServletContext().getRealPath("") + File.separator + UploadConstants.TEMP_DIR);
}
public void contextInitialized(ServletContextEvent sce) {
}
public void contextDestroyed(ServletContextEvent sce) {
deleteDir(sce.getServletContext().getRealPath("") + File.separator + UploadConstants.TEMP_DIR);
}
public void requestInitialized(ServletRequestEvent sre) {
}
private void deleteDir(final String dirPath) {
if (null == dirPath)
return;
File dir = new File(dirPath);
if (dir.exists() && dir.isDirectory()) {
File[] files = dir.listFiles();
if (null != files) {
for (File file : files) {
file.delete();
}
}
}
}
}
And mark your servlet with annotation as mentioned below.
@WebListener(value = "ContextListner")
This will delete temp file under temp directory or your specified directory.
public void requestDestroyed(ServletRequestEvent sre) {
deleteDir(sre.getServletContext().getRealPath("") + File.separator + UploadConstants.TEMP_DIR);
}
This method get call after response send back to client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With