001// Copyright (C) 2001 by Jason Hunter <jhunter_AT_acm_DOT_org>. 002// All rights reserved. Use of this class is limited. 003// Please see the LICENSE for more information. 004 005package com.oreilly.servlet; 006 007import java.io.*; 008import javax.servlet.*; 009import javax.servlet.http.*; 010 011/** 012 * A filter for easy semi-automatic handling of multipart/form-data requests 013 * (file uploads). The filter capability requires Servlet API 2.3. 014 * <p> 015 * See Jason Hunter's June 2001 article in JavaWorld for a full explanation of 016 * the class usage. 017 * 018 * @author <b>Jason Hunter</b>, Copyright © 2001 019 * @version 1.0, 2001/06/19 020 */ 021public class MultipartFilter implements Filter { 022 023 private FilterConfig config = null; 024 private String dir = null; 025 026 public void init(FilterConfig config) throws ServletException { 027 this.config = config; 028 029 // Determine the upload directory. First look for an uploadDir filter 030 // init parameter. Then look for the context tempdir. 031 dir = config.getInitParameter("uploadDir"); 032 if (dir == null) { 033 File tempdir = (File) config.getServletContext() 034 .getAttribute("javax.servlet.context.tempdir"); 035 if (tempdir != null) { 036 dir = tempdir.toString(); 037 } 038 else { 039 throw new ServletException( 040 "MultipartFilter: No upload directory found: set an uploadDir " + 041 "init parameter or ensure the javax.servlet.context.tempdir " + 042 "directory is valid"); 043 } 044 } 045 } 046 047 public void destroy() { 048 config = null; 049 } 050 051 public void doFilter(ServletRequest request, ServletResponse response, 052 FilterChain chain) throws IOException, ServletException { 053 HttpServletRequest req = (HttpServletRequest) request; 054 String type = req.getHeader("Content-Type"); 055 056 // If this is not a multipart/form-data request continue 057 if (type == null || !type.startsWith("multipart/form-data")) { 058 chain.doFilter(request, response); 059 } 060 else { 061 MultipartWrapper multi = new MultipartWrapper(req, dir); 062 chain.doFilter(multi, response); 063 } 064 } 065}