第一步我們需要 寫一個自己的html檔案 (根據自己的需求,進行編寫檔案模板)
<html><head><title>###title###</title><meta http- equiv="Content-Type" content="text/html; charset=gb2312"><LINK href="../css.css" rel=stylesheet type=text/css></head><body><table width="500" border="0" align="center" cellpadding="0"cellspacing="2"><tr><td align="center">###title###</td></tr><tr><td align="center">###author###</td></tr><tr><td align="center">###content###</td></tr></table></body></html>
第二部 採用struts2 作為action
public String downloadFiles() {try {HttpServletRequest request = ServletActionContext.getRequest();HttpServletResponse response = ServletActionContext.getResponse();// 解決中文亂碼問題response.setContentType("application/x-download;charset=utf-8");/** 讀模數板檔案內容 */FileInputStream input = new FileInputStream(new File(request.getRealPath("")+ "/WEB-INF/temp.html"));int byteLength = input.available();String title = "夢三國之下載任意格式檔案";String content = "測試。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。";String editer = "夢三國忠實粉絲";byte[] bytes = new byte[byteLength];input.read(bytes);input.close();String templateContent = new String(bytes);System.out.println("模板檔案內容===" + templateContent);templateContent = templateContent.replaceAll("###title###", title);templateContent = templateContent.replaceAll("###content###",content);templateContent = templateContent.replaceAll("###author###", editer);// 替換掉模板中相應的地方System.out.print("替換後的檔案內容" + templateContent);String name = "夢三國.html";// 下載檔案名稱byte[] outPutcontent = templateContent.getBytes();// 下載檔案內容response.setContentType("application/x-msdownload ");response.setHeader("Content-Disposition", "attachment;filename="+ new String(name.getBytes("gbk"), "iso-8859-1"));response.getOutputStream().write(outPutcontent); // 寫入檔案response.getOutputStream().flush();response.getOutputStream().close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}
最後我們可以通過訪問action的方式進行下載檔案
以上資訊希望對你有所協助。