打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
文件上传:读取文件流的形式

      传统的上传文件方式是首先将文件上传到指定路径,然后再从该路径下解析文件内容;这种方式实现比较繁琐,并且暴漏了文件上传的路径,造成了安全隐患。现在我们介绍的是另一种方式,直接读取文件流的方式,这种方式更加简单安全,而且不占用服务器内存。

一. jsp页面

1. list.jsp


  1. <ul>  
  2.    <li><a class="icon" title="导入文件" rel="dlg_import_comment" target="dialog"   
  3.    width="600" height="300" href="${ctx}/admin/comment/import.jsp"><span>导入文件</span></a></li>  
  4.    <li><a class="icon" title="下载文件模版" href="${ctx}/admin/comment/comment_template.xls"><span>下载文件Excel模版</span></a></li>  
  5.    <li>line</li>  
  6. </ul>  

2. import.jsp

  1. <%@ page contentType="text/html; charset=UTF-8" session="false" %>  
  2. <%@ include file="/WEB-INF/jspf/import.jspf" %>  
  3. <div class="pageContent">  
  4.     <form method="post" action="${ctx}/admin/comment/import.do" enctype="multipart/form-data"   
  5.     class="pageForm"  onsubmit="return iframeCallback(this, dialogAjaxDone);">  
  6.     <div class="pageFormContent" layoutH="56">  
  7.         <fieldset>  
  8.             <legend>请选择Excel文件,请务必按照规定的模版录入数据</legend>  
  9.             <dl class="nowrap">  
  10.                 <dd><input class="required" type="file" name="file"/></dd>  
  11.             </dl>  
  12.         </fieldset>  
  13.     </div>  
  14.     <div class="formBar">  
  15.         <ul>  
  16.             <li><div class="buttonActive"><div class="buttonContent"><button type="submit">导入</button></div></div></li>  
  17.             <li><div class="button"><div class="buttonContent"><button class="close" type="button">关闭</button></div></div></li>  
  18.         </ul>  
  19.     </div>  
  20.     </form>  
  21. </div>  

二. controller控制层

commentController.java

  1.        @RequestMapping(value = "/comment/import.do", method = RequestMethod.POST)  
  2.     public String doImport(HttpServletRequest req, HttpServletResponse resp) throws Exception {  
  3.         // 权限验证  
  4.         if (!AuthFacade.hasRight(AUTHFUNCTIONID_ALL, true, resp)) {  
  5.             return null;  
  6.         }  
  7.         boolean isMultipart = ServletFileUpload.isMultipartContent(req);  
  8.         if (!isMultipart) {  
  9.             showMessage(req, resp, 300, "没有选择文件,请重新上传", null, null);  
  10.         }  
  11.         // 计数器  
  12.         int count = 0;  
  13.         int fail = 0;  
  14.         StringBuffer failBuf = new StringBuffer();// 记录必填项为空的  
  15.         StringBuffer notExistsBuf = new StringBuffer(); // 记录不存在的  
  16.         StringBuffer lengthBuf = new StringBuffer(); // 记录超出长度的  
  17.         StringBuffer ruleBuf = new StringBuffer(); // 记录格式不正确的  
  18.         Integer statusCode = 200;  
  19.         String msg = "";  
  20.         Cell cell = null;  
  21.         DiskFileItemFactory factory = new DiskFileItemFactory();  
  22.         ServletFileUpload upload = new ServletFileUpload(factory);  
  23.         // 设置上传文件大小的上限10m,-1表示无上限  
  24.         upload.setFileSizeMax(1024 * 1024 * 10);  
  25.         upload.setHeaderEncoding("gbk");  
  26.         // 得到所有表单字段对象的集合  
  27.         List<FileItem> fileItems = null;  
  28.         try {  
  29.             fileItems = upload.parseRequest(req);  
  30.         } catch (FileUploadException e) {  
  31.             e.printStackTrace();  
  32.             showMessage(req, resp, 300, "解析上传的文件出错,请稍后重试", false, false);  
  33.         }  
  34.         if (fileItems == null || fileItems.isEmpty()) {  
  35.             showMessage(req, resp, 300, "文件为空,请重新上传", false, false);  
  36.         }  
  37.         // 迭代导入到表内数据  
  38.         Iterator it = fileItems.iterator();  
  39.         while (it.hasNext()) {  
  40.             FileItem fi = (FileItem) it.next();  
  41.             if (!fi.isFormField()) {  
  42.                 InputStream is = fi.getInputStream();  
  43.                 Workbook wb = null;  
  44.                 try {  
  45.                     wb = Workbook.getWorkbook(is);  
  46.                 } catch (Exception e) {  
  47.                     e.printStackTrace();  
  48.                     resp.setCharacterEncoding("UTF-8");  
  49.                     resp.getWriter().println(new JSONBuilder().put("statusCode", 300).put("message", "读取Excel表格出错,请检查Excel表格, 或者稍后重试").toString());  
  50.                     return null;  
  51.                 }  
  52.                 // 读取第一个工作本  
  53.                 Sheet sheet = wb.getSheet(0);  
  54.                 if (sheet != null) {  
  55.                     int rowNum = sheet.getRows();  
  56.                     // 聚合词  
  57.                     Comment comment = null;  
  58.                     CommentImg commentImg = null;  
  59.                     int groupId = 0; // 团购ID  
  60.                     int goodsId = 0; // 商品ID  
  61.                     int userId = 0; // 马甲ID  
  62.                     Date createAt = null; // 评论时间  
  63.                     String content = ""; // 评论  
  64.                     String url1 = ""; // 图片URL1  
  65.                     String url2 = ""; // 图片URL2  
  66.                     String url3 = ""; // 图片URL3  
  67.                     String url4 = ""; // 图片URL4  
  68.                     String url5 = ""; // 图片URL5  
  69.                     String uId = "";  
  70.                     String goId = "";  
  71.                     String grId = "";  
  72.                     String date = "";  
  73.                     long commentId = 0;  
  74.                     // 从第二行开始拿数据  
  75.                     for (int i = 1; i < rowNum; i++) {  
  76.                         List<String> str = new ArrayList<String>();  
  77.                         Cell[] cells = sheet.getRow(i);  
  78.                         if (cells != null && cells.length > 0) {  
  79.                             // A.团购ID  
  80.                             if (0 < cells.length) {  
  81.                                 cell = cells[0];  
  82.                             } else {  
  83.                                 cell = null;  
  84.                             }  
  85.                             if (cell != null) {  
  86.                                 grId = Utils.toInput(cell.getContents());  
  87.                                 if (Utils.isBlank(grId)) {  
  88.                                     fail++;  
  89.                                     failBuf.append((i + 1) + ";");  
  90.                                     continue;  
  91.                                 }  
  92.                                 groupId = Utils.intValue(grId, -1);  
  93.                                 if (groupId <= 0 || null == groupService.findGroup(groupId)) {  
  94.                                     fail++;  
  95.                                     notExistsBuf.append((i + 1) + ";");  
  96.                                     continue;  
  97.                                 }  
  98.                             } else {  
  99.                                 fail++;  
  100.                                 failBuf.append((i + 1) + ";");  
  101.                                 continue;  
  102.                             }  
  103.   
  104.                             // B.商品ID  
  105.                             if (1 < cells.length) {  
  106.                                 cell = cells[1];  
  107.                             } else {  
  108.                                 cell = null;  
  109.                             }  
  110.                             if (cell != null) {  
  111.                                 goId = Utils.toInput(cell.getContents());  
  112.                                 if (Utils.isBlank(goId)) {  
  113.                                     fail++;  
  114.                                     failBuf.append((i + 1) + ";");  
  115.                                     continue;  
  116.                                 }  
  117.                                 goodsId = Utils.intValue(goId, -1);  
  118.                                 if (goodsId <= 0 || null == goodsService.findGoods(goodsId)) {  
  119.                                     fail++;  
  120.                                     notExistsBuf.append((i + 1) + ";");  
  121.                                     continue;  
  122.                                 }  
  123.                             } else {  
  124.                                 fail++;  
  125.                                 failBuf.append((i + 1) + ";");  
  126.                                 continue;  
  127.                             }  
  128.   
  129.                             // C.马甲ID  
  130.                             if (2 < cells.length) {  
  131.                                 cell = cells[2];  
  132.                             } else {  
  133.                                 cell = null;  
  134.                             }  
  135.                             if (cell != null) {  
  136.                                 uId = Utils.toInput(cell.getContents());  
  137.                                 if (Utils.isBlank(uId)) {  
  138.                                     fail++;  
  139.                                     failBuf.append((i + 1) + ";");  
  140.                                     continue;  
  141.                                 }  
  142.                                 userId = Utils.intValue(uId, -1);  
  143.                                 Account account = userService.findAccount(userId);  
  144.                                 if (account == null) {  
  145.                                     fail++;  
  146.                                     notExistsBuf.append((i + 1) + ";");  
  147.                                     continue;  
  148.                                 }  
  149.                             } else {  
  150.                                 fail++;  
  151.                                 failBuf.append((i + 1) + ";");  
  152.                                 continue;  
  153.                             }  
  154.   
  155.                             // D.评论时间  
  156.                             if (3 < cells.length) {  
  157.                                 cell = cells[3];  
  158.                             } else {  
  159.                                 cell = null;  
  160.                             }  
  161.                             if (cell != null) {  
  162.                                 date = Utils.toInput(cell.getContents());  
  163.                                 if (Utils.isBlank(date)) {  
  164.                                     fail++;  
  165.                                     failBuf.append((i + 1) + ";");  
  166.                                     continue;  
  167.                                 }  
  168.                                 date = date.replace("/", "-");  
  169.                                 boolean isDate = Utils.isValidDate(date);  
  170.                                 if (isDate == true) {  
  171.                                     createAt = Utils.parseToDate(date, "yyyy-MM-dd HH:mm:ss");  
  172.                                 }  
  173.                                 if (createAt == null) {  
  174.                                     fail++;  
  175.                                     ruleBuf.append((i + 1) + ";");  
  176.                                     continue;  
  177.                                 }  
  178.                             } else {  
  179.                                 fail++;  
  180.                                 failBuf.append((i + 1) + ";");  
  181.                                 continue;  
  182.                             }  
  183.   
  184.                             // E.评论  
  185.                             if (4 < cells.length) {  
  186.                                 cell = cells[4];  
  187.                             } else {  
  188.                                 cell = null;  
  189.                             }  
  190.                             if (cell != null) {  
  191.                                 content = Utils.toInput(cell.getContents());  
  192.                                 if (Utils.isBlank(content)) {  
  193.                                     fail++;  
  194.                                     failBuf.append((i + 1) + ";");  
  195.                                     continue;  
  196.                                 }  
  197.                                 if (content.length() > 1000) {  
  198.                                     fail++;  
  199.                                     lengthBuf.append((i + 1) + ";");  
  200.                                     continue;  
  201.                                 }  
  202.                             } else {  
  203.                                 fail++;  
  204.                                 failBuf.append((i + 1) + ";");  
  205.                                 continue;  
  206.                             }  
  207.   
  208.                             // F.图片URL1  
  209.                             if (5 < cells.length) {  
  210.                                 cell = cells[5];  
  211.                             } else {  
  212.                                 cell = null;  
  213.                             }  
  214.                             if (cell != null) {  
  215.                                 url1 = Utils.toInput(cell.getContents());  
  216.                                 if (!Utils.isBlank(url1)) {  
  217.                                     if (url1.length() > 255) {  
  218.                                         fail++;  
  219.                                         lengthBuf.append((i + 1) + ";");  
  220.                                         continue;  
  221.                                     }  
  222.                                     str.add(url1);  
  223.                                 }  
  224.                             }  
  225.   
  226.                             // G.图片URL2  
  227.                             if (6 < cells.length) {  
  228.                                 cell = cells[6];  
  229.                             } else {  
  230.                                 cell = null;  
  231.                             }  
  232.                             if (cell != null) {  
  233.                                 url2 = Utils.toInput(cell.getContents());  
  234.                                 if (!Utils.isBlank(url2)) {  
  235.                                     if (url2.length() > 255) {  
  236.                                         fail++;  
  237.                                         lengthBuf.append((i + 1) + ";");  
  238.                                         continue;  
  239.                                     }  
  240.                                     str.add(url2);  
  241.                                 }  
  242.                             }  
  243.   
  244.                             // H.图片URL3  
  245.                             if (7 < cells.length) {  
  246.                                 cell = cells[7];  
  247.                             } else {  
  248.                                 cell = null;  
  249.                             }  
  250.                             if (cell != null) {  
  251.                                 url3 = Utils.toInput(cell.getContents());  
  252.                                 if (!Utils.isBlank(url3)) {  
  253.                                     if (url3.length() > 255) {  
  254.                                         fail++;  
  255.                                         lengthBuf.append((i + 1) + ";");  
  256.                                         continue;  
  257.                                     }  
  258.                                     str.add(url3);  
  259.                                 }  
  260.                             }  
  261.   
  262.                             // I.图片URL4  
  263.                             if (8 < cells.length) {  
  264.                                 cell = cells[8];  
  265.                             } else {  
  266.                                 cell = null;  
  267.                             }  
  268.                             if (cell != null) {  
  269.                                 url4 = Utils.toInput(cell.getContents());  
  270.                                 if (!Utils.isBlank(url4)) {  
  271.                                     if (url4.length() > 255) {  
  272.                                         fail++;  
  273.                                         lengthBuf.append((i + 1) + ";");  
  274.                                         continue;  
  275.                                     }  
  276.                                     str.add(url4);  
  277.                                 }  
  278.                             }  
  279.   
  280.                             // J.图片URL5  
  281.                             if (9 < cells.length) {  
  282.                                 cell = cells[9];  
  283.                             } else {  
  284.                                 cell = null;  
  285.                             }  
  286.                             if (cell != null) {  
  287.                                 url5 = Utils.toInput(cell.getContents());  
  288.                                 if (!Utils.isBlank(url5)) {  
  289.                                     if (url5.length() > 255) {  
  290.                                         fail++;  
  291.                                         lengthBuf.append((i + 1) + ";");  
  292.                                         continue;  
  293.                                     }  
  294.                                     str.add(url5);  
  295.                                 }  
  296.                             }  
  297.   
  298.                             int hasImg = 0;  
  299.                             if (null != str && str.size() > 0) {  
  300.                                 hasImg = 1;  
  301.                             }  
  302.                             comment = new Comment();  
  303.                             comment.setGroupId(groupId);  
  304.                             comment.setGoodsId(goodsId);  
  305.                             comment.setUserId(userId);  
  306.                             comment.setStatus(Comment.STATUS_NORMAL);  
  307.                             comment.setContent(content);  
  308.                             comment.setCreateAt(createAt);  
  309.                             comment.setHasImg(hasImg);  
  310.                             commentId = commentService.createComment(comment);  
  311.   
  312.                             for (String url : str) {  
  313.                                 commentImg = new CommentImg();  
  314.                                 commentImg.setCommentId(commentId);  
  315.                                 commentImg.setImgUrl(url);  
  316.                                 commentImg.setCreateBy(userId);  
  317.                                 commentService.createCommentImg(commentImg);  
  318.                             }  
  319.                             count++;  
  320.                         }  
  321.                     }  
  322.                 }  
  323.             }  
  324.         }  
  325.         resp.setCharacterEncoding("UTF-8");  
  326.         msg = "成功导入" + count + "条评论,失败" + ((0 > fail) ? 0 : fail) + "条!  ";  
  327.         if (fail > 0) {  
  328.             statusCode = 300;  
  329.             msg += "原因:";  
  330.             if (!Utils.isBlank(failBuf.toString())) {  
  331.                 msg += "必填项是否为空;行号为:" + failBuf.toString() + ";";  
  332.             }  
  333.             if (!Utils.isBlank(notExistsBuf.toString())) {  
  334.                 msg += "团购ID或商品ID或马甲ID不存在;行号为:" + notExistsBuf.toString() + ";";  
  335.             }  
  336.             if (!Utils.isBlank(lengthBuf.toString())) {  
  337.                 msg += "评论内容或图片url长度太长;行号为:" + lengthBuf.toString() + ";";  
  338.             }  
  339.             if (!Utils.isBlank(ruleBuf.toString())) {  
  340.                 msg += "评论时间格式不对;行号为:" + ruleBuf.toString() + ";";  
  341.             }  
  342.         }  
  343.         if (fail == 0) {  
  344.             showMessage(req, resp, statusCode, msg, true, true);  
  345.         } else {  
  346.             showMessage(req, resp, statusCode, msg, false, false);  
  347.         }  
  348.         return null;  
  349.     }  
       注意:传统文件上传方式需要在.xml文件配置文件上传监听multipartResolver,每次文件上传都会被监听到并先进行一次内容解析,再将解析后的内容传到controller层进行处理,而新方式是直接在controller层进行解析再处理,所以无需配置监听,若配置了监听二次解析是获取不到文件内容的。

  1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  2.         <property name="maxUploadSize" value="2000000"/>   
  3. </bean>  




本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Servlet中文件上传的几种方式
servlet 和JSP的上传下载
用commons.fileupload实现文件的上传和下载
JSP上传excel及excel插入至数据库实现方法代码
用commons-fileupload实现的上传文件同时提交form中的参数
Java文件上传组件 common-fileUpload 使用教程 - OPEN 开发经验库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服