upload_json.jsp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. <%@page import="java.security.SecureRandom"%>
  2. <%@page import="com.iamberry.wechat.tools.ImageUtils"%>
  3. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  4. <%@ page import="java.util.*,java.io.*" %>
  5. <%@ page import="java.text.SimpleDateFormat" %>
  6. <%@ page import="org.apache.commons.fileupload.*" %>
  7. <%@ page import="org.apache.commons.fileupload.disk.*" %>
  8. <%@ page import="org.apache.commons.fileupload.servlet.*" %>
  9. <%@ page import="org.json.simple.*" %>
  10. <%
  11. String saveServerPath = "/common/images/uploadimages/";
  12. // hostname
  13. String hostName = "";
  14. if (request.getRequestURL().indexOf("localhost") == -1) {
  15. hostName = "http://test.iamberry.com";
  16. } else {
  17. hostName = "http://localhost:" + request.getLocalPort();
  18. }
  19. //文件保存目录路径
  20. String savePath = pageContext.getServletContext().getRealPath(saveServerPath);
  21. //文件保存目录URL
  22. String saveUrl = request.getContextPath() + saveServerPath;
  23. //定义允许上传的文件扩展名
  24. HashMap<String, String> extMap = new HashMap<String, String>();
  25. extMap.put("image", "jpeg,jpg,png,gif");
  26. //最大文件大小
  27. long maxSize = 1000000;
  28. response.setContentType("text/html; charset=UTF-8");
  29. if(!ServletFileUpload.isMultipartContent(request)){
  30. out.println(getError("请选择文件。"));
  31. return;
  32. }
  33. //检查目录
  34. File uploadDir = new File(savePath);
  35. if(!uploadDir.isDirectory()){
  36. out.println(getError("上传目录不存在。"));
  37. return;
  38. }
  39. //检查目录写权限
  40. if(!uploadDir.canWrite()){
  41. out.println(getError("上传目录没有写权限。"));
  42. return;
  43. }
  44. String dirName = request.getParameter("dir");
  45. if (dirName == null) {
  46. dirName = "common/images";
  47. }
  48. if(!extMap.containsKey(dirName)){
  49. out.println(getError("目录名不正确。"));
  50. return;
  51. }
  52. //创建文件夹
  53. savePath += "/" + dirName + "/";
  54. saveUrl += "/" + dirName + "/";
  55. File saveDirFile = new File(savePath);
  56. if (!saveDirFile.exists()) {
  57. saveDirFile.mkdirs();
  58. }
  59. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  60. String ymd = sdf.format(new Date());
  61. savePath += ymd + "/";
  62. saveUrl += ymd + "/";
  63. File dirFile = new File(savePath);
  64. if (!dirFile.exists()) {
  65. dirFile.mkdirs();
  66. }
  67. FileItemFactory factory = new DiskFileItemFactory();
  68. ServletFileUpload upload = new ServletFileUpload(factory);
  69. upload.setHeaderEncoding("UTF-8");
  70. List items = upload.parseRequest(request);
  71. Iterator itr = items.iterator();
  72. while (itr.hasNext()) {
  73. FileItem item = (FileItem) itr.next();
  74. String fileName = item.getName();
  75. // 防止windows截断问题
  76. if (fileName != null && fileName.indexOf(":") != -1) {
  77. fileName = fileName.replaceAll(":", "");
  78. }
  79. long fileSize = item.getSize();
  80. if (!item.isFormField()) {
  81. //检查文件大小
  82. if(item.getSize() > maxSize){
  83. out.println(getError("上传文件大小超过限制。"));
  84. return;
  85. }
  86. //检查扩展名
  87. String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
  88. if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
  89. out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
  90. return;
  91. }
  92. // 根据文件魔数,校验文件类型
  93. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
  94. // 文件名使用安全的随机_时间_随机数.扩展名
  95. String newFileName = byte2hex(createRandomByte()) + "_" + df.format(new Date()) + "_" + new Random().nextInt(10000) + "." + fileExt;
  96. try{
  97. File uploadedFile = new File(savePath, newFileName);
  98. item.write(uploadedFile);
  99. }catch(Exception e){
  100. out.println(getError("上传文件失败。"));
  101. return;
  102. }
  103. // 系统任务,凡是上传的图片,系统认为全部不安全,默认缩放,改变文件结构,防止文件为木马
  104. if (ImageUtils.reSize(savePath + newFileName)) {
  105. JSONObject obj = new JSONObject();
  106. obj.put("error", 0);
  107. obj.put("url", hostName + saveUrl + newFileName);
  108. out.println(obj.toJSONString());
  109. } else {
  110. // 删除上传文件
  111. new File(savePath + newFileName).delete();
  112. out.println(getError("上传文件失败。"));
  113. return;
  114. }
  115. }
  116. }
  117. %>
  118. <%!
  119. /**
  120. * 创建一个安全的随机数组byte[]
  121. * @return
  122. */
  123. public byte[] createRandomByte() {
  124. try {
  125. SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  126. byte[] bytes = new byte[1024 / 8];
  127. random.nextBytes(bytes);
  128. int count = 10;
  129. byte[] seed = random.generateSeed(count);
  130. random = SecureRandom.getInstance("SHA1PRNG");
  131. random.setSeed(seed);
  132. SecureRandom random2 = SecureRandom.getInstance("SHA1PRNG");
  133. random2.setSeed(seed);
  134. return seed;
  135. } catch (Exception e) {
  136. return UUID.randomUUID().toString().getBytes();
  137. }
  138. }
  139. /**
  140. * byte[] 转 字符串
  141. * @param b
  142. * @return
  143. */
  144. public String byte2hex(byte[] b) {
  145. String hs = "";
  146. String stmp = "";
  147. for (int n = 0; n < b.length; n++) {
  148. stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
  149. if (stmp.length() == 1)
  150. hs = hs + "0" + stmp;
  151. else
  152. hs = hs + stmp;
  153. }
  154. return hs.toUpperCase();
  155. }
  156. private String getError(String message) {
  157. JSONObject obj = new JSONObject();
  158. obj.put("error", 1);
  159. obj.put("message", message);
  160. return obj.toJSONString();
  161. }
  162. %>