commons.fileupload 上传文件代码实现

package com.neeq.bpm.businessofcompany.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

public class CommonsFileUploadUtil {
	public static Map<String, String> doUpload(HttpServletRequest request,
			HttpServletResponse res) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(20 * 1024 * 1024); // 设定使用内存超过5M时,将产生临时文件并存储于临时目录中。
		Map reqParaMap = new HashMap();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			List items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String inputName = item.getFieldName();
				if (item.isFormField()) {
					String inputValue = item.getString();
					if (!StringUtils.isBlank(inputValue)) {
						inputValue = new String( inputValue.getBytes("ISO-8859-1"), "utf-8");
						reqParaMap.put(inputName, inputValue);
					}
				}else{
					reqParaMap.put(inputName, item);
//					String fileName = item.getName();
//					long fileSize = item.getSize();
//					OutputStream os = new FileOutputStream(new File(savePath,fileName));
//					InputStream is = item.getInputStream();
//					byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
//					int length = 0;
//					while ((length = is.read(buf)) > 0) {
//						os.write(buf, 0, length);
//					}
//					// 关闭流
//					os.flush();
//					os.close();
//					is.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return reqParaMap;
	}
}

猜你喜欢

转载自liushengit.iteye.com/blog/2301932