java實現下載任意格式檔案

來源:互聯網
上載者:User

第一步我們需要 寫一個自己的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的方式進行下載檔案

以上資訊希望對你有所協助。





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.