//相比smartUpload功能上感觉确实有点心有意力不足的感觉,就安全性判断后缀,smartUpload就非常方便。
public ModelAndView addFileUp(HttpServletRequest request,HttpServletResponse response) throws Exception { String preName = genName.doMake();//设置文件前缀名时间戳的MD5值 String fileName = null; //路径+文件名+后缀 String sucName = null; //最终名称 String oldName = null; //原始名称 //使用MultipartHttpServletRequest包装文件数据 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; //构建图片保存的目录 String logoPathDir = "/images/case/"; //得到图片保存目录的真实路径 String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir); //根据真实路径创建目录 File logoSaveFile = new File(logoRealPathDir); //判断组合的路径是否存在,不存在就创建 if (!logoSaveFile.exists()) { logoSaveFile.mkdirs(); } //页面控件的文件流,从页面上获取属性 MultipartFile multipartFile = multipartRequest.getFile("cpic"); // 获取文件名,即上传的原始文件名 oldName = multipartFile.getOriginalFilename(); System.out.println(multipartFile.getOriginalFilename()); //计算文件名长度(不包含后缀) int index = oldName.lastIndexOf("."); //如果文件名称<0 则用preName作为文件名 if (index == -1) { sucName = preName; } else { //否则就用自己定义的 sucName = preName + oldName.substring(index); } //设置属性值 //拼成完整的文件保存路径加文件 //得到的结果示范:d:webimagescase时间戳的MD5.gif fileName = logoRealPathDir + File.separator + sucName; File file = new File(fileName); try { //保存上传文件 multipartFile.transferTo(file); try { cases.setCtitle(request.getParameter("ctitle")); cases.setCurl(request.getParameter("curl")); cases.setCtime(ts); cases.setCcontext(request.getParameter("ccontext")); cases.setCpic("images/case/" + sucName); cases.setCtime(ts); if (cases != null && !"".equals(cases)) { casesBiz.doAdd(cases); mv.addObject("casesMsg", "提示:案例 <b>[" + cases.getCtitle()+ "]</b> 添加完成!"); } else { mv.addObject("casesMsg", "提示:案例 <b>[" + cases.getCtitle()+ "]</b> 添加失败!"); } } catch (Exception e) { // TODO: handle exception mv.addObject("casesMsg", "异常出现:"+e); } } catch (Exception e) { mv.addObject("casesMsg", "异常出现:"+e); } mv.setViewName("admin.do?method=cases"); return mv; }
XML
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- set the max upload size100MB --> <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> <property name="defaultEncoding"> <value>GBK</value> </property> </bean>
JAR文件下载地址:点击下载