之前准备采用ajax的方式下载txt文件的,但是发现网页直接打开可以打开的txt文件,所以只能采用比较原始的方式了,下面直接贴核心代码部分:
<div class="layui-btn-group demoTable" style="float: left"> <a href="download/txt" class="layui-btn" style="margin-left: 10px!important;">导出txt文档</a> </div>
以上就是前段核心部分,直接点击超链接进入controller层,下面贴出controller层代码:
@Controller @RequestMapping("/download") public class downloadController { @Resource private ItemsService itemsService; @RequestMapping(value="/txt",method = RequestMethod.GET) @ResponseBody public void queryAccount(HttpServletRequest req,HttpServletResponse resp) throws IOException { itemsService.download100Avaliable(req,resp); } }
下面贴出业务层代码:
@Override @Transactional(propagation = Propagation.REQUIRED,isolation= Isolation.DEFAULT,rollbackFor=Exception.class) public void download100Avaliable(HttpServletRequest req, HttpServletResponse resp) throws IOException { ResponseData rd=new ResponseData(); List<Account> objectList; /* BufferedWriter out=null;*/ ServletOutputStream outSTr = resp.getOutputStream();// 建立; BufferedOutputStream buff = null; try{ objectList=queryResultMapper.download100Avaliable();//先导出,实际为查询前100条记录 //另外,还需要删除这100个记录 queryResultMapper.delete100Avaliable();//再删除前100条记录 //拼凑字符串 StringBuilder content=new StringBuilder(); for(Account object:objectList){ content.append(object.get_account_account()); content.append(","); content.append(object.get_password()); content.append(System.getProperty("line.separator"));//换行 } SimpleDateFormat sFormat=new SimpleDateFormat("yyyy-MM-dd HHmmss"); Calendar calendar=Calendar.getInstance(); String fileName=sFormat.format(calendar.getTime()); resp.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt"); resp.setContentType("text/plain"); buff = new BufferedOutputStream(outSTr); buff.write(content.toString().getBytes(StandardCharsets.UTF_8)); buff.flush(); buff.close(); }catch (Exception ex){ ex.printStackTrace(); }finally { try { buff.close(); outSTr.close(); } catch (Exception e) { e.printStackTrace(); } } }