日期:2014-05-17 浏览次数:21125 次
public static String upload (String dir, HttpServletRequest request) { DiskFileUpload fu = new DiskFileUpload(); //最多上传3G的数据 fu.setSizeMax(1024 * 1024 * 1024 * 3); //超过1M的字段数据采用临时文件缓存 fu.setSizeThreshold(1024 * 1024); //采用默认的临时文件存储位置 //fu.setRepositoryPath(...); //设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码 fu.setHeaderEncoding("utf-8"); //得到所有表单字段对象的集合 List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } //处理每个表单字段 Iterator i = fileItems.iterator(); String targetName = null;//目标文件名 while (i.hasNext()){ FileItem fi = (FileItem) i.next(); if (!fi.isFormField()){ try { String pathSrc = fi.getName();//获取上传文件路径 pathSrc = new String(pathSrc.getBytes("ISO-8859-1"),"UTF-8"); if(pathSrc.trim().equals("")) { continue; } int start = pathSrc.lastIndexOf('\\'); String tempName = pathSrc.substring(start + 1);//获取上传文件名 String fileName = DateUtils.getNowLongTime();//新的文件名 if(tempName.indexOf(".") < 0){//如果文件没有后缀 targetName = fileName; }else{ int index = tempName.lastIndexOf("."); targetName = fileName+tempName.substring(index);//fileName+文件后缀 } File pathDest = new File(dir, targetName); fi.write(pathDest); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ fi.delete(); } } } return targetName.replace("\\", "/"); }