Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multipart Upload Servlet 3.0 - temporary files not deleting

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...");
    }
}   
like image 515
PrecisionPete Avatar asked Nov 11 '22 15:11

PrecisionPete


1 Answers

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.

like image 135
Bhupendra Piprava Avatar answered Nov 14 '22 22:11

Bhupendra Piprava