폼에 업로드된 파일이 있어요.

 servlet      :
String[] string = { "title", "type", "content"};//        name
String filename = FileSave.save(request, response, string); //              
map = FileSave.map;//   

 
다음은 공통 클래스입니다.
 
package cn.com.crystalnet.common;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
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.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * title:      
 * @author    
 *
 */

public class FileSave {
	
	public static Map map = null;

	public static String save(HttpServletRequest request, HttpServletResponse response,String[] paramName) {
		
		String u_name = null;
		
		map = new HashMap();
		
		final long MAX_SIZE = 3 * 1024 * 1024;//           3M
		//             
		final String[] allowedExt = new String[] { "gif","jpg","png","word","excel","txt","zip","ppt","pdf"  };
		response.setContentType("text/html");
		//        UTF-8,         
		response.setCharacterEncoding("UTF-8");

		//            ,        ServletFileUpload
		DiskFileItemFactory dfif = new DiskFileItemFactory();
		dfif.setSizeThreshold(4096);//                     ,   4K.            
		dfif.setRepository(new File(request.getRealPath("/")
				+ "ImagesUploadTemp"));//            ,web     ImagesUploadTemp  

		//             
		ServletFileUpload sfu = new ServletFileUpload(dfif);
		//         
		sfu.setSizeMax(MAX_SIZE);

		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//  request            
		List fileList = null;
	
		try {
			fileList = sfu.parseRequest(request);
			
			if (fileList != null) {
				for (Iterator itr = fileList.iterator(); itr.hasNext();) {
					FileItem fileItem = (FileItem) itr.next();
					for (int i = 0; i < paramName.length; i++) {
						if (fileItem.getFieldName().equalsIgnoreCase(
								paramName[i])) {
							map.put(fileItem.getFieldName(), new String(fileItem.getString().getBytes("ISO8859-1"),"UTF-8"));//     
						}
					}
				}
			}
			
			System.out.println(fileList.size());
		} catch (FileUploadException e) {//           
			if (e instanceof SizeLimitExceededException) {
				out.println("          :" + MAX_SIZE + "  <p />");
				out.println("<a href=\"UserCenter.jsp\" target=\"_top\">  </a>");

			}
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//       
		if (fileList == null || fileList.size() == 0) {
			out.println("       <p />");
			out.println("<a href=\"UserCenter.jsp\" target=\"_top\">  </a>");

		}
		//          
		Iterator fileItr = fileList.iterator();
		//         

		while (fileItr.hasNext()) {
			FileItem fileItem = null;
			String path = null;
			long size = 0;
			//       
			fileItem = (FileItem) fileItr.next();
			//     form            (<input type="text" /> )
			if (fileItem == null || fileItem.isFormField()) {
				continue;
			}
			//          
			path = fileItem.getName();
			//        
			size = fileItem.getSize();
			if ("".equals(path) || size == 0) {
				out.println("       <p />");
				out.println("<a href=\"UserCenter.jsp\" target=\"_top\">  </a>");
				break;

			}

			//           
			String t_name = path.substring(path.lastIndexOf("\\") + 1);
			//         (          )
			String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
			//                  
			int allowFlag = 0;
			int allowedExtCount = allowedExt.length;
			for (; allowFlag < allowedExtCount; allowFlag++) {
				if (allowedExt[allowFlag].equals(t_ext))
					break;
			}
			if (allowFlag == allowedExtCount) {
				out.println("          <p />");
				for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
					out.println("*." + allowedExt[allowFlag]
							+ "&nbsp;&nbsp;&nbsp;");
				out
						.println("<p /><a href=\"UserCenter.jsp\" target=\"_top\">  </a>");

			}

			long now = System.currentTimeMillis();
			//                  
			String prefix = String.valueOf(now);
			//            ,   web     ImagesUploaded   
			u_name = request.getRealPath("/") + "Back\\mailUpload\\"
					+ prefix + "." + t_ext;
			try {
				//     
				fileItem.write(new File(u_name));
				u_name = "mailUpload/"+ prefix + "." + t_ext;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
			
		return u_name;
	}

}

좋은 웹페이지 즐겨찾기