KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > oreilly > servlet > MultipartFilter


1 // Copyright (C) 2001 by Jason Hunter <jhunter_AT_acm_DOT_org>.
2
// All rights reserved. Use of this class is limited.
3
// Please see the LICENSE for more information.
4

5 package com.oreilly.servlet;
6
7 import java.io.*;
8 import javax.servlet.*;
9 import javax.servlet.http.*;
10
11 /**
12  * A filter for easy semi-automatic handling of multipart/form-data requests
13  * (file uploads). The filter capability requires Servlet API 2.3.
14  * <p>
15  * See Jason Hunter's June 2001 article in JavaWorld for a full explanation of
16  * the class usage.
17  *
18  * @author <b>Jason Hunter</b>, Copyright &#169; 2001
19  * @version 1.0, 2001/06/19
20  */

21 public class MultipartFilter implements Filter {
22
23   private FilterConfig config = null;
24   private String JavaDoc dir = null;
25
26   public void init(FilterConfig config) throws ServletException {
27     this.config = config;
28
29     // Determine the upload directory. First look for an uploadDir filter
30
// init parameter. Then look for the context tempdir.
31
dir = config.getInitParameter("uploadDir");
32     if (dir == null) {
33       File tempdir = (File) config.getServletContext()
34                   .getAttribute("javax.servlet.context.tempdir");
35       if (tempdir != null) {
36         dir = tempdir.toString();
37       }
38       else {
39         throw new ServletException(
40           "MultipartFilter: No upload directory found: set an uploadDir " +
41           "init parameter or ensure the javax.servlet.context.tempdir " +
42           "directory is valid");
43       }
44     }
45   }
46
47   public void destroy() {
48     config = null;
49   }
50
51   public void doFilter(ServletRequest request, ServletResponse response,
52                      FilterChain chain) throws IOException, ServletException {
53     HttpServletRequest req = (HttpServletRequest) request;
54     String JavaDoc type = req.getHeader("Content-Type");
55
56     // If this is not a multipart/form-data request continue
57
if (type == null || !type.startsWith("multipart/form-data")) {
58       chain.doFilter(request, response);
59     }
60     else {
61       MultipartWrapper multi = new MultipartWrapper(req, dir);
62       chain.doFilter(multi, response);
63     }
64   }
65 }
66
Popular Tags