一:思路 1.0 使用场景用例: 数据导入功能使用模板文件作为参考,先从服务器中下载模板,然后编辑实际数据信息,再上传文件信息。 1.1 首先在相应的模板目录中(…\Choice\template)存放好模板文件,接下来就是实现导入了。
二:步骤 在页面定义“下载模板”按钮,发送导出功能请求; 在控制层中直接调用应用层/工具类里的下载方法。
/** * 下载模板信息 */ @RequestMapping(value = "/downloadTemplate") public void downloadTemplate(HttpServletResponse response,HttpServletRequest request) throws IOException { DataSourceSwitch.setDataSourceType(DataSourceInstances.SCM);//选择数据源 supplyService.downloadTemplate(response, request); //调用业务层方法 } /** * 下载模板信息 * * @param response * @param request * @throws IOException */ public void downloadTemplate(HttpServletResponse response,HttpServletRequest request) throws IOException { //下载模板,调用公用方法,适用windows和linux,templete文件夹下文件的下载 PublicExportExcel.downloadTemplate(response, request, "物资编码导入模板.xls"); // 调用工具类的实现方法 } /** * 下载模板信息 * 适用于windows和linux * @param response * @param request * @param templeteName * @throws IOException */ public static void downloadTemplate(HttpServletResponse response,HttpServletRequest request,String templeteName) throws IOException { OutputStream outp = null; FileInputStream in = null; try { String fileName = templeteName; //要下载的模板文件 if(templeteName!=null){ if(!templeteName.endsWith(".xls")){ fileName = templeteName + ".xls"; } } String ctxPath = request.getSession().getServletContext().getRealPath(File.separator) + File.separator + "template" + File.separator; String filedownload = ctxPath + fileName; fileName = URLEncoder.encode(fileName, "UTF-8"); // 要下载的模板所在的绝对路径 response.reset(); response.addHeader("Content-Disposition", "attachment; filename="+fileName); response.setContentType("application/octet-stream;charset=UTF-8"); outp = response.getOutputStream(); in = new FileInputStream(filedownload); byte[] b = new byte[1024]; int i = 0; while ((i = in.read(b)) > 0) { outp.write(b, 0, i); } outp.flush(); } catch (Exception e) { System.out.println("Error!"); e.printStackTrace(); } finally { if (in != null) { in.close(); in = null; } if (outp != null) { outp.close(); outp = null; } } }