上传文件工具类

依赖:

commons-logging

commons-io

commons-fileupload

代码:

/*
 * UploadUtil.java
 * @author dawn.liu  2011-9-17 
 * @version 1.0
 * Copyright (c) 2011-2012,  dawn.liu. All rights reserved.
 */
package com.lyjilu.util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author  dawn.liu 2011-9-17 Copyright (c) 2011-2012,  dawn.liu All rights reserved.
 * @version 1.0 
 * 上传处理工具类,主要处理request请求,封装request信息等
 *        
 */
public class UploadUtil {
	private static Log log = LogFactory.getLog(UploadUtil.class);

	/**
	 * 默认临时存储目录
	 */
	public static String TEMPREPOSITORY = System.getProperty("java.io.tmpdir");
	/**
	 * 在内存中的最大限度
	 */
	public static int SIZETHRESHOLD = 1000000;

	/**
	 * 最大上传文件大小
	 */
	public static int SIZEMAX = 5024000;
	/**
	 * 变量,永远在request.setAttribute的时候的键,方便统一取值
	 */
	public String reqattributename = "__UploadFile";

	/**
	 * 默认构造,
	 */
	public UploadUtil() {

	}

	/**
	 * 设置放到requestattr里时的key变量
	 * 
	 * @param reqattributename
	 *            变量
	 */
	public void setReqattributename(String reqattributename) {
		this.reqattributename = reqattributename;
	}

	/**
	 * 设置默认存放路径
	 * 
	 * @param temprepository
	 *            路径
	 */
	public UploadUtil(String temprepository) {
		this(temprepository, 0, 0);
	}

	/**
	 * 构造,设置在内存中的最大限度
	 * 
	 * @param sizethreshold
	 *            在内存中的最大限度
	 */
	public UploadUtil(int sizethreshold) {
		this(null, sizethreshold, 0);
	}

	/**
	 * 设置各个上传限制参赛
	 * 
	 * @param temprepository
	 *            临时目录
	 * @param sizethreshold
	 *            内存最大限度
	 * @param sizemax
	 *            最大上传文件
	 */
	public UploadUtil(String temprepository, int sizethreshold, int sizemax) {
		if (temprepository != null && !"".equals(temprepository))
			TEMPREPOSITORY = temprepository;
		if (sizethreshold > 0 && sizethreshold < Integer.MAX_VALUE)
			SIZETHRESHOLD = sizethreshold;
		if (sizemax > 0 && sizemax < Integer.MAX_VALUE)
			SIZEMAX = sizethreshold;
	}

	/**
	 * 上传文件集合
	 */
	private Map<String, FileItem> files = new HashMap<String, FileItem>();

	/**
	 * 文本域数据集合
	 */
	private Map<String, Object> fields = new HashMap<String, Object>();

	public Map<String, FileItem> getFiles() {
		return files;
	}

	public void setFiles(Map<String, FileItem> files) {
		this.files = files;
	}

	public Map<String, Object> getFields() {
		return fields;
	}

	public void setFields(Map<String, Object> fields) {
		this.fields = fields;
	}

	/**
	 * 
	 * 处理request,封装表单和上传的文件
	 * 
	 * @param request
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void parseRequest(HttpServletRequest request) throws Exception {
		request.setCharacterEncoding("UTF-8");
		// 判断是否为上传
		if (ServletFileUpload.isMultipartContent(request)) {
			// 初始一个DiskFileItemFactory
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置临时存放目录
			File file = new File(TEMPREPOSITORY);
			if (!file.exists() || !file.isDirectory()) {
				file.mkdirs();
			}
			factory.setRepository(file);
			// 设置在内存中的最大限度
			factory.setSizeThreshold(SIZETHRESHOLD);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置最大上传文件大小
			upload.setSizeMax(SIZEMAX);
			List<FileItem> items = null;
			try {
				// 格式化
				items = upload.parseRequest(request);
			} catch (Exception e) {
				log.debug("上传文件格式化request错误", e);
				e.printStackTrace();
				if (e instanceof SizeLimitExceededException) {
					throw new Exception("ERROR:上传文件过大,文件最大:" + SIZEMAX / 1024
							+ "KB");
				} else {
					throw new Exception("格式化请求错误" + e.getMessage());
				}
			}
			// 取得item的迭代对象
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					String fieldName = new String(item.getFieldName().getBytes(
							"ISO-8859-1"), "UTF-8");
					String fieldValue = new String(item.getString().getBytes(
							"ISO-8859-1"), "UTF-8");
					if (fields.containsKey(fieldName)) {
						Object obj = fields.get(fieldName);
						if (obj instanceof List) {
							List<Object> ob = (List<Object>) obj;
							ob.add(fieldValue);
						} else {
							List<Object> list = new ArrayList<Object>();
							list.add(obj);
							list.add(fieldValue);
							fields.remove(fieldName);
							fields.put(fieldName, list);
						}
					} else
						fields.put(fieldName, fieldValue);
				} else if (item.get() != null && item.get().length > 0) {
					files.put(item.getFieldName(), item);
				}
			}
			request.setAttribute(reqattributename, this);
		} else {
			log.debug("上传文件ERROR:该请求不是上传文件");
			throw new Exception("ERROR:该请求不是上传文件 ");
		}
	}

}

servlet中用法

UploadUtil upbase =  new UploadUtil();
		try {
			upbase.parseRequest(request);
		} catch (Exception e) {
			e.printStackTrace();
			
		}
doSomething1(upbase);
 

相关推荐