第一种形式,是以流的开式直接response,适用于数据量不是很大的情况下。
第二种形式,是先将要下载的文件写到后台的一个文件或者excel 中,然后再进行下载。
第一种实现:
package com.smartdot.pdm.business.corp.magazine.util; import java.io.BufferedOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import com.smartdot.pdm.business.corp.magazine.bean.MagazineBean; public class MagazineUtils { // 输出TXT public static void writeToTxt(HttpServletResponse response, List list) { response.setContentType("text/plain");// 一下两行关键的设置 response.addHeader("Content-Disposition", "attachment;filename=期刊出版社.txt");// filename指定默认的名字 BufferedOutputStream buff = null; StringBuffer write = new StringBuffer(); String tab = " "; String enter = "\r\n"; MagazineBean magazine; ServletOutputStream outSTr = null; try { outSTr = response.getOutputStream();// 建立 buff = new BufferedOutputStream(outSTr); for (int i = 0; i < list.size(); i++) { magazine = (MagazineBean) list.get(i); write.append("期刊名称:" + tab); write.append(delNull(magazine.getChineseName()) + enter); write.append(enter); } buff.write(write.toString().getBytes("UTF-8")); buff.flush(); buff.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { buff.close(); outSTr.close(); } catch (Exception e) { e.printStackTrace(); } } } public static String delNull(Date date) { String returnStr=""; if (date!=null) { SimpleDateFormat sf=new SimpleDateFormat("yyyy年MM月"); returnStr=sf.format(date); } return returnStr; } public static String delNull(String str) { String returnStr=""; if (StringUtils.isNotBlank(str)) { returnStr=str; } return returnStr; } }
第二种实现:
// 输出TXT public static void writeToTxt(HttpServletRequest request, List list) { FileOutputStream outSTr = null; BufferedOutputStream Buff = null; String path = request.getSession().getServletContext().getRealPath( "upordown/down/model/magazinePub.txt"); String tab = " "; String enter = "\r\n"; MagazineBean magazine; StringBuffer write ; try { outSTr = new FileOutputStream(new File(path)); Buff = new BufferedOutputStream(outSTr); for (int i = 0; i < list.size(); i++) { magazine = (MagazineBean) list.get(i); write = new StringBuffer(); write.append("期刊名称:" + tab); write.append(delNull(magazine.getTenet()) + enter); write.append(enter); Buff.write(write.toString().getBytes("UTF-8")); } Buff.flush(); Buff.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { Buff.close(); outSTr.close(); } catch (Exception e) { e.printStackTrace(); } } }
下载的代码:
//下载 public ActionForward downFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String name=request.getParameter("filename"); // TODO Auto-generated method stub try { String path = request.getSession().getServletContext().getRealPath( "upordown/down/model/"+name); File file = new File(path); String filename = file.getName(); // 取得文件的扩展名ext String ext = filename.substring(filename.lastIndexOf(".") + 1) .toUpperCase(); InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); response.addHeader("Content-Length", "" + file.length()); // 设置返回的文件类型 OutputStream toClient = new BufferedOutputStream(response .getOutputStream()); // 得到向客户端输出二进制数据的对象 // 根据扩展名声称客户端浏览器mime类型 if (ext.equals("xls")) response.setContentType("application/msexcel"); else response.setContentType("application/octet-stream"); // 设置返回的文件类型 toClient.write(buffer); // 输出数据 toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); return mapping.findForward("error"); } return null; }
客户端调用
//下载txt function downTxt(){ window.open ('${pageContext.request.contextPath}/business/magazineAction.do?method=downFile&filename=magazinePub.txt', '文件下载', 'height=300, width=400, top='+(screen.availHeight-300)/2+', left='+(screen.availWidth-400)/2+', toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no'); } //导出txt function exportTxt(){ var queryForm=document.queryForm; var minRow=queryForm.minRow.value; var maxRow=queryForm.maxRow.value; var totalCnt="${totalCnt}"; if(StringUtils.isBlank(totalCnt)){ totalCnt=0; } if(Validator.Validate(2)){ minRow=parseInt(minRow); maxRow=parseInt(maxRow); // if(maxRow-minRow+1>1000){ // alert("每次最多可以导出1000条数据"); // return ; // } if(maxRow>totalCnt){ alert("结束记录数不能等大于总记录条数:"+totalCnt); return ; } if(maxRow<minRow){ alert("结束记录数不能小于开始记录数"); return ; } req.setRequestMethod("post"); var url="${pageContext.request.contextPath}/business/magazineAction.do?method=doExportTxt&orderColumn=${orderColumn}&orderType=${orderType}&queryCondition="+encodeURIComponent('${queryCondition}')+"&maxRow="+maxRow+"&minRow="+minRow+"&isDecorator=false"; req.setRequestURL(url); req.setAsync(true); req.setMethodOnSuccess(displayMsg); req.setRequestHeader("Content-Type","text/html;charset=gbk"); req.send(null); } }