title: File upload - The proper way to use apache's DiskFileItemFactory and ServletFileUpload.parseRequest
body: <p>I have the following legacy code which which is used as part of our file upload process.</p>
  
  <pre><code>    HttpServletRequest httpRequest = (HttpServletRequest) request;
      List&lt;FileItem&gt; uploadedFiles = new ArrayList&lt;FileItem&gt;();
      try {
          // File size settings excluded here
          DiskFileItemFactory factory = new DiskFileItemFactory();
          ServletFileUpload upload = new ServletFileUpload(factory);
          uploadedFiles = upload.parseRequest(httpRequest);
  </code></pre>
  
  <p>I am revisiting this code and I am concerned about the file cleanup.  Given that the FileCleaningTracker is never set in the DiskFileItemFactory I assume the files are never being deleted, but it's not clear to me from the javadocs. Specifically I'm not sure if their use of "automatically" means the file cleanup happens out of the box.</p>
  
  <blockquote>
    <p>Temporary files are automatically deleted as soon as they are no
    longer needed. (More precisely, when the corresponding instance of
    java.io.File is garbage collected.) Cleaning up those files is done by
    an instance of FileCleaningTracker, and an associated thread.</p>
  </blockquote>
  
  <p><strong>What is the proper way to use the ServletFileUpload, where the FileItemFactory is of type DiskFileItemFactory, to parse the HttpServletRequest?</strong>  I want to make sure there is no memory leak.</p>
  
  <p>I'm leaning towards making the following change, but I don't feel all that confident in this.</p>
  
  <pre><code>    HttpServletRequest httpRequest = (HttpServletRequest) request;
      List&lt;FileItem&gt; uploadedFiles = new ArrayList&lt;FileItem&gt;();
      try {
          // File size settings excluded here
          DiskFileItemFactory factory = new DiskFileItemFactory();
          factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(httpRequest.getSession().getServletContext()));
          ServletFileUpload upload = new ServletFileUpload(factory);
          uploadedFiles = upload.parseRequest(httpRequest);           
  </code></pre>