文件上传过滤类

package com.mvc.interceptor;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.DeferredFileOutputStream;

import com.mvc.filter.MVCHttpParams;

public class UploadInterceptor extends MVCInterceptorAdapter{

	@Override
	public String invoke(MVCHttpParams params) {
		HttpServletRequest request=params.getRequest();
		String contexttype=request.getContentType();
		if(!contexttype.equals("application/x-www-form-urlencoded")){
			HttpServletResponse response=params.getResponse();
			HttpSession session=request.getSession();
			response.setCharacterEncoding("UTF-8");
			DiskFileItemFactory diskfactory=new DiskFileItemFactory();
			diskfactory.setSizeThreshold(4096);
			File f=new File(request.getSession().getServletContext().getRealPath("/")+"temp");
			if(!f.exists()){
				f.mkdir();
			}
			diskfactory.setRepository(f);
			ServletFileUpload sfu=new ServletFileUpload();
			sfu.setFileItemFactory(diskfactory);
			sfu.setFileSizeMax(3*1024*1024);
			try {
				List<FileItem> filelist=sfu.parseRequest(request);
				for(FileItem item:filelist){
					if(item.isFormField()){
						String name=item.getFieldName();
						request.setAttribute(name, item.getString());
						if(null==session.getAttribute("UPLOADREQUEST")){
							session.setAttribute("UPLOADREQUEST", "true");
						}
						continue;
					}else{
						session.setAttribute("FILEITEM", item);
					}
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
		return null;
	}

	@Override
	public String doAfter(MVCHttpParams params) {
		HttpSession session=params.getRequest().getSession();
		if(session.getAttribute("FILEITEM")!=null){
			FileItem item=(FileItem)session.getAttribute("FILEITEM");
			DeferredFileOutputStream dfos=null;
			try {
				dfos = (DeferredFileOutputStream)item.getOutputStream();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			File file=dfos.getFile();
			file.delete();
			session.removeAttribute("FILEITEM");
			session.removeAttribute("UPLOADREQUEST");
		}
		return null;
	}

	
}

相关推荐