Friday, February 13, 2009

How to integrate Struts with Commons-file upload

Step 1: Update the commons-fileupload to the version 1.2.1 and commons-io to the version 1.3.x. This is required because; the entire solution is based on the FileTracker class which is available in commons-io 1.3. And, commons-fileupload has also needed to be upgraded because, FileTracker can be associated only with DiskFileItemFactory, which is part of commons-fileupload 1.2.1, but can not be associated with any of the classes referenced in the CommonsMutltipartRequest handler, which is used as part of the struts application.

Step 2: Extend the CommonsMutltipartRequestHandler to EYCommonsMultipartRequestHandler and override the method, handleRequest(). The part of the implementation is given below.

 

// Create a factory for disk-based file items

DiskFileItemFactory factory = new DiskFileItemFactory();

 

// Set factory constraints

factory.setSizeThreshold(maxMemorySize);

factory.setRepository(tempDirectory);

 

//getting handle of the file cleaning tracker

FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(context);

 

//setting the file cleaning tracker, so that when ever the //factory is getting garbage collected, the associated //resources, including the temp file also will be deleted.

factory.setFileCleaningTracker(fileCleaningTracker);

 

// Create a new file upload handler

ServletFileUpload upload = new ServletFileUpload(factory);

 

// Set overall request size constraint

upload.setSizeMax(yourMaxRequestSize);

 

// Parse the request

List /* FileItem */ items = upload.parseRequest(request);

 

 

Step 3: Add the newly created EYMultipartRequestHandler, to the struts configuration, under element tag as given below.

 

<controller>

<set-property property="multipartClass" value="com.ey.nexgen.struts.fileupload.EYCommonsMultipartRequestHandle”/>

controller>

Step 4: As mentioned earlier, temporary files are deleted automatically, if they are no longer used (more precisely, if the corresponding instance of java.io.File) is garbage collected. This is done silently by the org.apache.commons.io.FileCleaner class, which starts a reaper thread.

This reaper thread should be stopped, if it is no longer needed. In a servlet environment, this is done by using a special servlet context listener, called FileCleanerCleanUp . To do so, add a section like the following to your web.xml:

  ...

 

   

      org.apache.commons.fileupload.servlet.FileCleanerCleanup

   

 

  ...

1 comment:

  1. can i lock temporary files (block deletion temporary file ) until I finish my treatment.
    because I get error file not found

    ReplyDelete