下载 文件 java_java实现下载任意格式文件

该博客介绍了如何使用Java实现下载任意格式文件的方法。首先创建一个HTML模板文件,然后在Struts2 Action中处理下载请求,设置响应内容类型、处理中文乱码问题,并将模板内容替换为实际数据,最后通过HTTP响应输出文件内容,触发浏览器下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值