java实现下载任意格式文件

第一步我们需要 写一个自己的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的方式进行下载文件

以上信息希望对你有所帮助!





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值