package com.dubh.common.file;
import java.io.File;
import java.util.Iterator;
import java.util.UUID;

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

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.util.RequestUtil;

/**
 * @author 作者姓名: dubaohui
 * @version 创建时间：2015-5-18 下午8:29:45 
 * 
 * 类说明 :文件上传
 */
public class UploadFile {

	
	/**
	 * 多文件上传
	 * @param HttpServletRequest
	 * @param HttpServletResponse
	 * @return JSONArray
	 * */
	public static  JSONArray uploadmore(HttpServletRequest request,
			HttpServletResponse response) {
		JSONArray array = new JSONArray();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					JSONObject object = new JSONObject();
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (myFileName.trim() != "") {
							String oldname = myFileName;
							object.put("filename",oldname);
							object.put("filekj", file.getName());
							//定义上传路径命名新文件夹
							String mkfile = RequestUtil.getid(0);
							//判断新文件夹是否存在
							String paths = request.getSession().getServletContext().getRealPath("attached")+"/"+mkfile;
							File newfile = new File(paths);
							if(!newfile.exists()){
								newfile.mkdir();
							}
							//新文件名称
							String newfilename=RequestUtil.getid(3)+"."+RequestUtil.getExtensionName(myFileName);
							//文件绝对路径
							String path = paths+"/"+ newfilename;
							File localFile = new File(path);
							file.transferTo(localFile);
							//文件相对路径
							String filepath = "/"+"attached"+"/"+mkfile+"/"+newfilename;
							object.put("filepath",filepath);
							// 记录上传该文件后的时间
							int finaltime = (int) System.currentTimeMillis();
							int time = finaltime - pre;
							object.put("time",time);
							array.put(object);
						}	
					}
				}

			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return array;
	}

	
	
	
	
	/***
	 * 
	 * 单文件上传
	 * @param HttpServletRequest
	 * @param HttpServletResponse
	 * @return JSONObject
	 * */
	public static  JSONObject uploadone(HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject object = new JSONObject();
		String oldname ="";
		String filepath="";
		int time  =0;
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (myFileName.trim() != "") {
							oldname = myFileName;
							
							//定义上传路径命名新文件夹
							String mkfile = RequestUtil.getid(5);
							//判断新文件夹是否存在
							String paths = request.getSession().getServletContext().getRealPath("attached")+"/"+mkfile;
							File newfile = new File(paths);
							if(!newfile.exists()){
								newfile.mkdir();
							}
							//新文件名称
							String newfilename=RequestUtil.getid(3)+"."+RequestUtil.getExtensionName(myFileName);
							//文件绝对路径
							String path = paths+"/"+ newfilename;
							File localFile = new File(path);
							file.transferTo(localFile);
							//文件相对路径
							filepath = "/"+"attached"+"/"+mkfile+"/"+newfilename;
							
						}
					}
					// 记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					time = finaltime - pre;
					
				}

			}
			object.put("time",time);
			object.put("filename",oldname);
			object.put("filepath",filepath);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return object;
	}
	
	
	
	/**
	 * 多文件上传(仅供与检测端使用)
	 * @param HttpServletRequest
	 * @param HttpServletResponse
	 * @return JSONArray
	 * */
	public static  JSONArray uploadmore2(HttpServletRequest request,
			HttpServletResponse response,String id) {
		JSONArray array = new JSONArray();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					JSONObject object = new JSONObject();
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					synchronized (file) {
					if (file != null) {
						// 取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (myFileName.trim() != "") {
							String oldname = myFileName;
							oldname=oldname.replaceAll("_", "");
							object.put("filename",oldname);
							object.put("filekj", file.getName());
							object.put("filesize", file.getSize()/1024);
							String type=oldname.substring((oldname.lastIndexOf(".")+1),oldname.length());
							object.put("type", type);
							//定义上传路径命名新文件夹
							String mkfile =id;
							//判断新文件夹是否存在
							String paths = request.getSession().getServletContext().getRealPath("attached")+"/"+mkfile;
							File newfile = new File(paths);
							if(!newfile.exists()){
								newfile.mkdir();
							}
							//新文件名称
//							String newfilename=RequestUtil.getid(3)+"."+RequestUtil.getExtensionName(myFileName);
							String newfilename=UUID.randomUUID()+"."+RequestUtil.getExtensionName(myFileName);
							//文件绝对路径
//							String path = paths+"/"+ oldname;
							String path = paths+"/"+ newfilename;
							File localFile = new File(path);
							file.transferTo(localFile);
							//文件相对路径
//							String filepath = "/"+"attached"+"/"+mkfile+"/"+oldname;
							String filepath = "/"+"attached"+"/"+mkfile+"/"+newfilename;
							object.put("filepath",filepath);
							// 记录上传该文件后的时间
							int finaltime = (int) System.currentTimeMillis();
							int time = finaltime - pre;
							System.out.println(file.getName()+":"+filepath);
							object.put("time",time);
							array.put(object);
							}	
						}
					}
				}

			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return array;
	}

}
