标签:lis blog parse new etc mfa 必须 trace ring
l commons-fileupload.jar,核心包
l commons-io.jar,依赖包
1 import java.io.File; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 6 import javax.servlet.http.HttpServletRequest; 7 8 import org.apache.commons.fileupload.FileItem; 9 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 10 import org.apache.commons.fileupload.servlet.ServletFileUpload; 11 import org.apache.commons.io.FilenameUtils; 12 13 public class MyFileUpload { 14 15 public static Map<String,String[]> getFileUpload(HttpServletRequest request){ 16 //1获取表单数据 17 //*1.1创建工厂类DiskFileItemFactory对象 18 DiskFileItemFactory factory = new DiskFileItemFactory(); 19 //*1.2使用工厂创建解析对象 20 ServletFileUpload fileUpload = new ServletFileUpload(factory); 21 //*1.3使用解析器来解析request对象 22 //用于封装普通表单项的数据 23 Map<String, String[]> map = new HashMap<String,String[]>(); 24 25 try { 26 List<FileItem> list = fileUpload.parseRequest(request); 27 for (FileItem item : list) { 28 if(item.isFormField()){ 29 //如果里面封装的是普通数据 30 String name = item.getFieldName(); //字段名 31 String value = item.getString("UTF-8"); //字段的值 32 map.put(name,new String[]{value}); 33 }else{ 34 //里面是文件表单数据 35 String filename = item.getName();//上传的文件名 36 String extension = FilenameUtils.getExtension(filename);//文件的扩展名 37 //上传的文件的扩展名不能是jsp和exe 38 if(!(extension.equals("jsp")||extension.equals("exe"))){ 39 //创建目录 40 File storeDir = new File(request.getServletContext().getRealPath("/WEB-INF/upload")); 41 if(!storeDir.exists()){ 42 storeDir.mkdirs(); //目录不存在就创建目录 43 } 44 //处理文件名 45 if(filename !=null&&(!"".equals(filename))){ 46 filename = FilenameUtils.getName(filename); 47 }else{ 48 continue; 49 } 50 51 //目录打散 52 String childDir = makeChildDir(storeDir,filename); 53 filename = childDir+File.separator+filename; 54 //System.out.println(storeDir); 55 try { 56 item.write(new File(storeDir,filename));//!!!!!!!存储路径 57 item.delete(); 58 } catch (Exception e) { 59 e.printStackTrace(); 60 } 61 map.put(item.getFieldName(), new String[]{filename}); 62 } 63 } 64 } 65 } catch (Exception e) { 66 e.printStackTrace(); 67 } 68 return map; 69 } 70 private static String makeChildDir(File storeDir, String filename) { 71 int hashcode = filename.hashCode(); //返回字符串转换的32位的hashcode码 72 String code = Integer.toHexString(hashcode);//把hashcode转换为16进制的字符 73 74 String childDir = code.charAt(0)+File.separator+code.charAt(1);// a/b 75 //创建指定目录 76 File file = new File(storeDir,childDir); //根据storeDir的路径创建一个新的childDir路径 77 if(!file.exists()){ 78 file.mkdirs(); 79 } 80 return childDir; 81 } 82 83 }
标签:lis blog parse new etc mfa 必须 trace ring
原文地址:http://www.cnblogs.com/id-666/p/7461107.html