最近做了一个需要文件上传并解析保存到数据库的功能,为方便自己后续review,特整理如下:
前端代码(纯属测试使用):
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ include file="/WEB-INF/views/include/taglib.jsp"%> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=320, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>文件上传页面</title> <link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/static/redpacket/css/demo.css"/> <style type="text/css"> body,html,h3,p{ margin: 0; padding: 0; font-size: 14px; background: #fafafa; } .upload{ margin-left: 10px; } .upload:first-child{ margin-left: 0; } </style> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <div class="content_report"> <p>请您填写<span class="fontBold">产品图片、防伪码图片、联系电话、购买地点</span>,完成信息反馈</p> <div class="report_content"> <div class="report_pic"> <span class="uploadSpan">上传文件:</span> <a class="upload" href="#"> <img src="${ctxStatic}/img/addPic.png" width="70" height="70" id="img1"/> <input class="change" type="file" name="file" id="fileUpload"/> </a> </div> <div class="report_place"> <span>登录名:</span> <input type="text" id="location" name="loginName"> </div> <div class="report_tel"> <span>密码:</span> <input type="text" name="pwd" id="tel" /> </div> <button class="report_button wid100" id="commit">提交</button> </div> </div> </form> <script src="<%=request.getContextPath()%>/static/redpacket/js/jquery-1.6.2.min.js" type="text/javascript"></script> <script type="text/javascript"> $("#commit").click(function(){ var fd= new FormData(); var file=$("#fileUpload").get(0).files[0]; var name=$("#location").val(); var pwd = $("#tel").val(); fd.append("file",file); fd.append("loginName",name); fd.append("pwd",pwd); $.ajax({ type:"POST", contentType:false, processData:false, url:"${ctx}/redpacket/up/text", data:fd, dataType:"JSON", success:function(obj){ if (obj.state==1){ alert(obj.message); }else{ alert(obj.message); } } }); }); </script> </body> </html>
上述图片的路径等自己按照本地的修改,或者直接去掉就行,需要注意的是:
1.form表单要添加属性 enctype='multipart/form-data',使用Formdata提交
后台代码:
package com.weichai.modules.redpacket.web; import com.alibaba.fastjson.JSON; import com.weichai.modules.redpacket.entity.ResponseResult; import com.weichai.modules.redpacket.entity.RpCodeBinging; import com.weichai.modules.redpacket.service.RpCodeBingingService; import com.weichai.modules.redpacket.service.RpUpFileService; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.annotations.Param; import org.apache.log4j.Logger; import org.apache.poi.ss.formula.functions.T; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.util.ArrayList; import java.util.List; /** * autro: * 同步二维码文件类 */ @Controller @RequestMapping(value = "${adminPath}/redpacket/up") public class RpUpFileTextController { @Autowired private RpUpFileService rpUpFileService; @Autowired private RpCodeBingingService rpCodeBingingService; private static final Logger LOG = Logger.getLogger(RpUpFileTextController.class); /** * 使用multipartFile接收二维码文件,并将文件保存到数据库 * @param loginName * @param pwd * @param file * @return */ @RequestMapping(value = "text") @ResponseBody public ResponseResult<T> upFileText(@RequestParam("loginName") String loginName, @RequestParam("pwd") String pwd, @RequestParam("file") MultipartFile file){ ResponseResult<T> rr = new ResponseResult<>(); try { if (!StringUtils.isNotBlank(loginName)||!StringUtils.isNotBlank(pwd)||null==file){ rr.setState(ResponseResult.STATE_ERROR); rr.setMessage("请保证参数的有效性!!"); return rr; } //将文件同步到本地保存,返回路径 String result = rpUpFileService.upFileTxt(loginName,pwd,file); if ("0".equals(result)){ rr.setState(ResponseResult.STATE_ERROR); rr.setMessage("用户名或密码错误!"); }else if ("1".equals(result)){ rr.setState(ResponseResult.STATE_ERROR); rr.setMessage("文件不能为空!"); } else if ("".equals(result)){ rr.setState(ResponseResult.STATE_ERROR); rr.setMessage("上传失败!"); }else{ LOG.error("---------------开始解析文件----------------"); //解析文件,返回实体对象集合 List<RpCodeBinging> list = getRpCodeBingingsList(result); LOG.error("---------------解析文件完毕----------------"); LOG.error("---------------开始存储数据库----------------"); //保存到数据库 int n = list.size(); int m = (int)Math.ceil(n/2000.0); if (n<=2000){ int num= rpCodeBingingService.saveList(list); setResult(rr, num); }else{ int sum=0; for (int i=0;i<m;i++){ int num=0; if(i!=(m-1)){ num =rpCodeBingingService.saveList(list.subList(i*2000, Math.min((i+1)*2000, list.size()-1))); }else{ num =rpCodeBingingService.saveList(list.subList(i*2000, Math.min((i+1)*2000, list.size()-1)+1)); } sum+=num; } setResult(rr, sum); } LOG.error("---------------存储数据库完毕----------------"); } } catch (IOException e) { LOG.error("未知异常:"+e); rr.setState(ResponseResult.STATE_ERROR); rr.setMessage("系统异常,上传失败!"); e.printStackTrace(); } return rr; } /** * 设定返回值 * @param rr * @param sum */ private void setResult(ResponseResult<T> rr, int sum) { if (sum>0){ rr.setState(ResponseResult.STATE_OK); rr.setMessage("上传成功!"); }else{ rr.setState(ResponseResult.STATE_ERROR); rr.setMessage("数据可能存在重复,上传失败!"); } } /** * 测试上传界面 * @return */ @RequestMapping(value="show") public String showUpText(){ return "modules/redpacket/upFile"; } /** * 封装方法,解析.txt文件,返回实体对象list集合 * @return * @throws IOException */ private static List<RpCodeBinging> getRpCodeBingingsList(String result) throws IOException {
//将文件转换为字节输入流 InputStream in = new FileInputStream(result);
//将字符流转换为缓冲字符流 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"utf-8")); String data=""; StringBuffer buffer = new StringBuffer(); while((data=bufferedReader.readLine())!=null){ buffer.append(data); } String str = buffer.toString();
//RpCodeBinging需要改成你自己需解析对应的实体对象 List<RpCodeBinging> list = JSON.parseArray(str,RpCodeBinging.class); return list; } }
package com.weichai.modules.redpacket.service; import com.weichai.common.config.Global; import com.weichai.common.mapper.JsonMapper; import com.weichai.modules.redpacket.web.RpUpFileTextController; import org.apache.log4j.Logger; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; @Service public class RpUpFileService { private static final Logger LOG = Logger.getLogger(RpUpFileTextController.class); public String upFileTxt(String loginName, String pwd , MultipartFile file){ LOG.error("-----------------开始上传文件---------------------"); //判断用户名及密码 if(!("Rp_File".equals(loginName))||!("Rp_#0".equals(pwd))){ return "0"; } if (null==file){ return "1"; }
//获取文件名字 String pathname = file.getOriginalFilename();
//获取文件后缀,即类型 String suffix = pathname.substring(pathname.lastIndexOf(".")); String path = Global.getConfig("fileurl"); String filepath=""; if (".txt".equals(suffix)){ try { long l = System.currentTimeMillis(); //new日期对象 Date date = new Date(l); //转换提日期输出格式 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd ss"); String name = dateFormat.format(date)+".txt"; filepath=path+File.separator+name; File tfile = new File(path); if (!tfile.exists()){ tfile.mkdir(); } file.transferTo(new File(filepath)); LOG.error("-----------------上传文件完毕---------------------"); } catch (Exception e) { e.printStackTrace(); LOG.error("上传失败原因:"+e); } } return filepath; } }
所有代码完毕。。如有问题欢迎大家指出,,