View Javadoc

1   package net.sourceforge.blogentis.utils.filters;
2   
3   import java.io.File;
4   import java.io.IOException;
5   
6   import javax.servlet.Filter;
7   import javax.servlet.FilterChain;
8   import javax.servlet.FilterConfig;
9   import javax.servlet.ServletException;
10  import javax.servlet.ServletRequest;
11  import javax.servlet.ServletResponse;
12  import javax.servlet.http.HttpServletRequest;
13  
14  /***
15   * A filter for easy semi-automatic handling of multipart/form-data requests
16   * (file uploads). The filter capability requires Servlet API 2.3.
17   * <p>
18   * See Jason Hunter's June 2001 article in JavaWorld for a full explanation of
19   * the class usage.
20   * 
21   * @author <b>Jason Hunter </b>, Copyright &#169; 2001
22   * @version 1.0, 2001/06/19
23   */
24  public class MultipartFilter
25          implements Filter {
26  
27      private String dir = null;
28      private String encoding = null;
29  
30      public void init(FilterConfig config)
31              throws ServletException {
32          // Determine the upload directory. First look for an uploadDir filter
33          // init parameter. Then look for the context tempdir.
34          dir = config.getInitParameter("uploadDir");
35          if (dir == null) {
36              File tempdir = (File)config.getServletContext()
37                      .getAttribute("javax.servlet.context.tempdir");
38              if (tempdir != null) {
39                  dir = tempdir.toString();
40              } else {
41                  throw new ServletException(
42                      "MultipartFilter: No upload directory found: set an uploadDir "
43                              + "init parameter or ensure the javax.servlet.context.tempdir "
44                              + "directory is valid");
45              }
46          }
47          encoding = config.getInitParameter("forceEncoding");
48      }
49  
50      public void destroy() {
51  
52      }
53  
54      public void doFilter(ServletRequest request, ServletResponse response,
55                           FilterChain chain)
56              throws IOException, ServletException {
57          HttpServletRequest req = (HttpServletRequest)request;
58          String type = req.getHeader("Content-Type");
59  
60          // response.setContentType("text/html; charset=UTF-8");
61          // If this is not a multipart/form-data request continue
62          if (type == null || !type.startsWith("multipart/form-data")) {
63  //            if (encoding != null) {
64  //                request.setCharacterEncoding(encoding);
65  //            }
66              chain.doFilter(request, response);
67          } else {
68              MultipartWrapper multi = new MultipartWrapper(req, dir, encoding);
69              chain.doFilter(multi, response);
70          }
71      }
72  }