<%@page import="java.security.SecureRandom"%> <%@page import="com.iamberry.wechat.tools.ImageUtils"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.*,java.io.*" %> <%@ page import="java.text.SimpleDateFormat" %> <%@ page import="org.apache.commons.fileupload.*" %> <%@ page import="org.apache.commons.fileupload.disk.*" %> <%@ page import="org.apache.commons.fileupload.servlet.*" %> <%@ page import="org.json.simple.*" %> <% String saveServerPath = "/common/images/uploadimages/"; // hostname String hostName = ""; if (request.getRequestURL().indexOf("localhost") == -1) { hostName = "http://test.iamberry.com"; } else { hostName = "http://localhost:" + request.getLocalPort(); } //文件保存目录路径 String savePath = pageContext.getServletContext().getRealPath(saveServerPath); //文件保存目录URL String saveUrl = request.getContextPath() + saveServerPath; //定义允许上传的文件扩展名 HashMap extMap = new HashMap(); extMap.put("image", "jpeg,jpg,png,gif"); //最大文件大小 long maxSize = 1000000; response.setContentType("text/html; charset=UTF-8"); if(!ServletFileUpload.isMultipartContent(request)){ out.println(getError("请选择文件。")); return; } //检查目录 File uploadDir = new File(savePath); if(!uploadDir.isDirectory()){ out.println(getError("上传目录不存在。")); return; } //检查目录写权限 if(!uploadDir.canWrite()){ out.println(getError("上传目录没有写权限。")); return; } String dirName = request.getParameter("dir"); if (dirName == null) { dirName = "common/images"; } if(!extMap.containsKey(dirName)){ out.println(getError("目录名不正确。")); return; } //创建文件夹 savePath += "/" + dirName + "/"; saveUrl += "/" + dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); String fileName = item.getName(); // 防止windows截断问题 if (fileName != null && fileName.indexOf(":") != -1) { fileName = fileName.replaceAll(":", ""); } long fileSize = item.getSize(); if (!item.isFormField()) { //检查文件大小 if(item.getSize() > maxSize){ out.println(getError("上传文件大小超过限制。")); return; } //检查扩展名 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if(!Arrays.asList(extMap.get(dirName).split(",")).contains(fileExt)){ out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。")); return; } // 根据文件魔数,校验文件类型 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // 文件名使用安全的随机_时间_随机数.扩展名 String newFileName = byte2hex(createRandomByte()) + "_" + df.format(new Date()) + "_" + new Random().nextInt(10000) + "." + fileExt; try{ File uploadedFile = new File(savePath, newFileName); item.write(uploadedFile); }catch(Exception e){ out.println(getError("上传文件失败。")); return; } // 系统任务,凡是上传的图片,系统认为全部不安全,默认缩放,改变文件结构,防止文件为木马 if (ImageUtils.reSize(savePath + newFileName)) { JSONObject obj = new JSONObject(); obj.put("error", 0); obj.put("url", hostName + saveUrl + newFileName); out.println(obj.toJSONString()); } else { // 删除上传文件 new File(savePath + newFileName).delete(); out.println(getError("上传文件失败。")); return; } } } %> <%! /** * 创建一个安全的随机数组byte[] * @return */ public byte[] createRandomByte() { try { SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] bytes = new byte[1024 / 8]; random.nextBytes(bytes); int count = 10; byte[] seed = random.generateSeed(count); random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(seed); SecureRandom random2 = SecureRandom.getInstance("SHA1PRNG"); random2.setSeed(seed); return seed; } catch (Exception e) { return UUID.randomUUID().toString().getBytes(); } } /** * byte[] 转 字符串 * @param b * @return */ public String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) hs = hs + "0" + stmp; else hs = hs + stmp; } return hs.toUpperCase(); } private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toJSONString(); } %>