首页 > 代码库 > SpringMVC 文件下载的配置
SpringMVC 文件下载的配置
页面:
<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; }}
只是记录一下。
SpringMVC 文件下载的配置
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。