SpringMVC文件的上传下载及数据库EXCEL导出

来源:互联网 发布:数据库流程图怎么话 编辑:程序博客网 时间:2024/06/14 08:19

前段时间要做文件的上传下载,现在把它写出来,供大家分享

首先是excel导出数据库

@RequestMapping("/exportCustomer")      public void exportCustomer(ModelMap model,HttpServletRequest request,HttpServletResponse response) {      SysUser models = UserHelper.getCurrentUser();        //TODO 如需添加条件          //model.addAttribute("username", nameStr);          //获取需要导出的数据List  //        List<CMcustomer> cusList=customerService.exportCustomer(model); //        List<Units> cusList = unitsService.zTreeAll(models.getId());    List<Units> all = unitsService.getAll();            //使用方法生成excle模板样式                  HSSFWorkbook workbook = unitsService.createExcel(all, request);          SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 定义文件名格式            try {          //定义excle名称 ISO-8859-1防止名称乱码              String msg = new String(                      ("组织机构信息_" + format.format(new Date()) + ".xls").getBytes(),                      "ISO-8859-1");              // 以导出时间作为文件名              response.setContentType("application/vnd.ms-excel");              response.addHeader("Content-Disposition", "attachment;filename="                      + msg);              ServletOutputStream outputStream = response.getOutputStream();            workbook.write(response.getOutputStream());          } catch (IOException e) {  //            log.error(e);          e.getStackTrace();        }      } 

然后是文件的上传功能

@RequestMapping(value="/formExcel",method = RequestMethod.POST)@ResponseBodypublic String formExcel( MultipartFile upExcel ){        try {String originalFilename = upExcel.getOriginalFilename();if(originalFilename==null){return "请选择要上传的文件";}String uploadPath = "upload/document"+ "/" + UUID.getUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));FileStorageHelper.transferFile(upExcel.getInputStream(), uploadPath);Document document = new Document();document.setUrl(uploadPath);documentService.save1(document);return "上传文件成功";} catch (Exception e) {e.printStackTrace();return "导入文件失败";}}

最后是文件下载

/**    *  下载文件    * @param urldata 文件路径    * @param response    */   @RequestMapping("/download")       public void download(String urldata,HttpServletResponse response){          String rootPath = SpringMVCUtil.getRequest().getSession().getServletContext().getRealPath("/");// 获取项目根目录       try {File file = new File(rootPath+urldata);// path是根据日志路径和文件名拼接出来的String filename = file.getName();// 获取日志文件名称InputStream fis = new BufferedInputStream(new FileInputStream(rootPath+urldata));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();response.reset();// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));response.addHeader("Content-Length", "" + file.length());OutputStream os = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");os.write(buffer);// 输出文件os.flush();os.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}              }
文件的下载可以自己选择要下载的位置

前台页面要这样请求下载的地址

//下载function updateLoad(id,name) {        $.ajax({type:"POST",url:"/Document/download",data:{"urldata":id},success:function(msg){window.open('/Document/download?urldata='+id); }});// alert(id);}

这就是基本的代码篇了,欢迎互相交流


1 0