2、Spring.xml配置文件上传
<!--8、配置文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <property name="maxUploadSizePerFile" value="1048576"/><!--单个文件最大限制1M--> <property name="maxUploadSize" value="10485760"/><!--最大上传限制10M--> </bean>1.2、js—ajax异步请求:要依赖于jqury.form函数库
<script src="/js/jquery-1.10.2.min.js"></script> <script src="/js/jquery.form.js"></script> <!--1.script不能简写为单标签 2.jquery.form需要jquery的支持,放后面--> <script> $('#upload').change(function () { var f={ type:'post', url:'/emp2/upload', dataType:'json', success:function (data) { $('#Img').attr("src",data); $('#hd').val(data) } }; $('#add').ajaxSubmit(f); }) </script>1.3、controller层
@RequestMapping("/upload") @ResponseBody//图片上传 public String upload(MultipartFile mf, HttpSession session){ //图片上传的路径 String realPath = session.getServletContext().getRealPath("/img"); System.out.println(realPath); //获取图片名称 String filename = mf.getOriginalFilename(); //加上唯一的前缀 filename=System.currentTimeMillis()+ UUID.randomUUID().toString()+filename; try { //开始上传 File file = new File(realPath, filename); if (!file.exists()){ file.mkdirs(); } mf.transferTo(file);//上传 } catch (IOException e) { System.out.println("图片上传失败!"); System.out.println(e.getMessage()); } session.setAttribute("imgurl","/img/"+filename); //响应图片在服务器中的路径 return JSON.toJSONString("/img/"+filename); }2.2、controller层
//实现图片下载 @RequestMapping("/down") public void down(String filename, HttpSession session, HttpServletResponse response){ try { //先找到图片的位置 String realPath = session.getServletContext().getRealPath("/img"); filename=filename.substring(4); System.out.println(realPath+filename); //一个头两个流 filename=new String(filename.getBytes("GBK"),"ISO-8859-1");//处理图片中文乱码 response.setHeader("content-disposition","attachment;filename"+filename); FileInputStream is = new FileInputStream(realPath + filename); ServletOutputStream os = response.getOutputStream(); IOUtils.copy(is,os); }catch (Exception e){ try { response.sendRedirect("/");//图片下载异常,重定向去首页 } catch (IOException e1) { e1.printStackTrace(); } } }2、js—ajax异步请求
<script> $('#delBat').click(function () { //获取到选中的ids 送到后台 var ids=new Array(); $('.checkNow:checked').each(function () { var id=$(this).val() ids.push(id); }); $.post("/emp2/batDel",{ids:ids.toString()},function (data) { alert('删除成功!') location.href='/index.jsp'; }) }) //实现全选和全部选 $('#checkAll').click(function () { if ($(this).prop("checked")){ $(".checkNow").prop("checked",true) } else { $(".checkNow").prop("checked",false) } }); </script>3、controller层
@RequestMapping("/batDel") @ResponseBody public void batDel(Integer[] ids){ System.out.println(Arrays.toString(ids)); service.batDel(ids); }4、service层
@Override//批量删除 public void batDel(Integer[] ids) { EmpExample example = new EmpExample(); EmpExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(Arrays.asList(ids)); empMapper.deleteByExample(example); }