第一步我们需要 写一个自己的html文件 (根据自己的需求,进行编写文件模板)
###title###cellspacing="2">
###title######author######content###第二部 采用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 block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
最后我们可以通过访问action的方式进行下载文件
以上信息希望对你有所帮助!