package westion.www.utls;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.codec.binary.Base64;

/**
 * 
 * ÎÄ¼þÉÏ´«ºÍÉ¾³ý¹¤¾ßÀà
 * 
 * ¾ßÌå²½Öè£º 1£©»ñµÃ´ÅÅÌÎÄ¼þÌõÄ¿¹¤³§ DiskFileItemFactory Òªµ¼°ü 2£© ÀûÓÃ request »ñÈ¡ ÕæÊµÂ·¾¶ £¬¹©ÁÙÊ±ÎÄ¼þ´æ´¢£¬ºÍ
 * ×îÖÕÎÄ¼þ´æ´¢ £¬ÕâÁ½¸ö´æ´¢Î»ÖÃ¿É²»Í¬£¬Ò²¿ÉÏàÍ¬ 3£©¶Ô DiskFileItemFactory ¶ÔÏóÉèÖÃÒ»Ð© ÊôÐÔ 4£©¸ßË®Æ½µÄAPIÎÄ¼þÉÏ´«´¦Àí
 * ServletFileUploadupload = new ServletFileUpload(factory);
 * Ä¿µÄÊÇµ÷ÓÃparseRequest£¨request£©·½·¨ »ñµÃ FileItem ¼¯ºÏlist £¬ 5£©ÔÚ FileItem ¶ÔÏóÖÐ »ñÈ¡ÐÅÏ¢£¬ ±éÀú£¬
 * ÅÐ¶Ï ±íµ¥Ìá½»¹ýÀ´µÄÐÅÏ¢ ÊÇ·ñÊÇ ÆÕÍ¨ÎÄ±¾ÐÅÏ¢ Áí×ö´¦Àí 6£© µÚÒ»ÖÖ. ÓÃµÚÈý·½ Ìá¹©µÄ item.write( new
 * File(path,filename) ); Ö±½ÓÐ´µ½´ÅÅÌÉÏ µÚ¶þÖÖ. ÊÖ¶¯´¦Àí
 * 
 * 
 * @version 1.0, 2014-4-6
 * @author westion
 * @since JDK1.7
 */
public class FileTool {

	/**
	 * @param request
	 *            HttpServletRequest
	 * @param dir
	 *            String ÉÏ´«ÎÄ¼þ´æ·ÅµÄÎ»ÖÃ
	 * @return filename String ÉÏ´«ÎÄ¼þµÄµØÖ·£¬Ïà¶Ô¸ùÄ¿Â¼
	 * */
	public static String fileUpload(HttpServletRequest request, String dir)
			throws Exception {
		String filename = null;

		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			String path = request.getServletContext().getRealPath(dir);
			factory.setRepository(new File(path));
			// ÉèÖÃ »º´æµÄ´óÐ¡£¬µ±ÉÏ´«ÎÄ¼þµÄÈÝÁ¿³¬¹ý¸Ã»º´æÊ±£¬Ö±½Ó·Åµ½ ÔÝÊ±´æ´¢ÊÒ
			factory.setSizeThreshold(1024 * 1024);

			// ¸ßË®Æ½µÄAPIÎÄ¼þÉÏ´«´¦Àí
			ServletFileUpload upload = new ServletFileUpload(factory);
			// upload.setHeaderEncoding("UTF-8");
			// ¿ÉÒÔÉÏ´«¶à¸öÎÄ¼þ
			System.out.println(upload.getHeaderEncoding());
			List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

			for (FileItem item : list) {
				// »ñÈ¡±íµ¥µÄÊôÐÔÃû×Ö
				String name = item.getFieldName();

				// Èç¹û»ñÈ¡µÄ ±íµ¥ÐÅÏ¢ÊÇÆÕÍ¨µÄ ÎÄ±¾ ÐÅÏ¢
				if (item.isFormField()) {
					// »ñÈ¡ÓÃ»§¾ßÌåÊäÈëµÄ×Ö·û´® £¬Ãû×ÖÆðµÃÍ¦ºÃ£¬ÒòÎª±íµ¥Ìá½»¹ýÀ´µÄÊÇ ×Ö·û´®ÀàÐÍµÄ
					//»ñÈ¡×Ö·ûµÄ±àÂë
					String value = item.getString("UTF-8");
					if (value.equals("")) {
						value = null;
					}
					request.setAttribute(name, value);
				}
				// ¶Ô´«ÈëµÄ·Ç ¼òµ¥µÄ×Ö·û´®½øÐÐ´¦Àí £¬±ÈÈçËµ¶þ½øÖÆµÄ Í¼Æ¬£¬µçÓ°ÕâÐ©
				else {
					String value = item.getName();
					// ²»´øÎÄ¼þ
					if (value == null || value.equals("")) {
						continue;
					}
					// Ë÷Òýµ½×îºóÒ»¸ö·´Ð±¸Ü
					int start = value.lastIndexOf(".");
					String type = value.substring(start); // ´øÒ»¸öµã

					// ÓÃÊ±¼äºÍsession±àÂë£¬±£Ö¤Î¨Ò»ÐÔ
					String encodeToString = Base64.encodeBase64String((request
							.getSession().getId() + new Date().getTime())
							.getBytes());
					filename = encodeToString + type;
					// ÕæÕýÐ´µ½´ÅÅÌÉÏ
					// ËüÅ×³öµÄÒì³£ ÓÃexception ²¶×½
					// item.write( new File(path,filename) );//µÚÈý·½Ìá¹©µÄ
					// ÊÖ¶¯Ð´µÄ
					File file = new File(path, filename);
					OutputStream out = new FileOutputStream(file);
					InputStream in = item.getInputStream();

					int length = 0;
					byte[] buf = new byte[1024];

					// in.read(buf) Ã¿´Î¶Áµ½µÄÊý¾Ý´æ·ÅÔÚ buf Êý×éÖÐ
					while ((length = in.read(buf)) != -1) {
						// ÔÚ buf Êý×éÖÐ È¡³öÊý¾Ý Ð´µ½ £¨Êä³öÁ÷£©´ÅÅÌÉÏ
						out.write(buf, 0, length);

					}
					in.close();
					out.close();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return filename;

	}

	/**
	 * @param filePath
	 *            String ÎÄ¼þµÄÂ·¾¶
	 * */
	public static void deleteFile(String filePath) {
		try {
			File file = new File(filePath);
			file.delete();
		} catch (Exception e) {
			throw e;
		}

	}
}
