您的位置:首页 > 编程语言 > Java开发

java实现下载任意格式文件

2013-07-02 16:45 405 查看
第一步我们需要 写一个自己的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 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的方式进行下载文件

以上信息希望对你有所帮助!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: