页面:
<fieldset> <legend>Download annotator list</legend> <img src="pages/tools/listannotator/img/text.png" id="downloadAnnotatorListCsvImg"/> <img src="pages/tools/listannotator/img/xls.png"/> </fieldset>
JS代码:
$("#downloadAnnotatorListCsvImg").click( function(){ var wnd=openCenterWindow(APP_NAME+"downloadAnnotatorListCsv.html","Download Annotator List in CSV format",400,300); } ); var APP_NAME="/rttsbiz2/"; function openCenterWindow(url,windowName,width,height){ var left = (window.screen.availWidth-10-width)/2; var top = (window.screen.availHeight-30-height)/2; var wnd=window.open(url,windowName,"height="+height+",width="+width+",top="+top+",left="+left+",resizable=yes,scrollbars=yes,status=no,location=no,"); return wnd; }
Controller代码:
@RequestMapping("/downloadAnnotatorListCsv") public ModelAndView download(HttpServletRequest request,HttpServletResponse response){ String fileName="download-single.txt"; response.reset();// 不加这一句的话会出现下载错误 response.setHeader("Content-disposition", "attachment; filename="+fileName);// 设定输出文件头 response.setContentType("text/x-plain");// 定义输出类型 try { ServletOutputStream out = response.getOutputStream(); String path = System.getProperty("java.io.tmpdir") + "\\poem.txt"; File file = new File(path); FileOutputStream fos = new FileOutputStream(file); Writer writer = new OutputStreamWriter(fos, "utf-8"); String text="Hello!download!"; writer.write(text); writer.close(); fos.close(); FileInputStream fis = new java.io.FileInputStream(file); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(4096); byte[] cache = new byte[4096]; for (int offset = fis.read(cache); offset != -1; offset = fis.read(cache)) { byteOutputStream.write(cache, 0, offset); } byte[] bt = null; bt = byteOutputStream.toByteArray(); out.write(bt); out.flush(); out.close(); fis.close(); if(file.exists()){ file.delete(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
只是记录一下。