java文件下载

本文介绍了一种在Java代码中实现文件下载的方法,并针对文件不存在的情况进行了异常处理,避免了直接使用超链接导致的问题。通过示例代码展示了如何设置HTTP头部信息以正确显示中文文件名。

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

在网页编程时,文件下载,有一种方法就是用超链接直接指向文件所在路径(url),但该方法有一些弊端,一是在某些浏览器中会直接在网页中打开所在下载的文件,另外一个就是遇到中文文件名时,也会容易出错。解决这一问题,可直接在java代码中编写下载,如下:

public void downLoad(String id) throws IOException
{
DocZhidu bo=(DocZhidu)dao.getObjectById(DocZhidu.class, id);
File file = new File(ServletActionContext.getServletContext().getRealPath(DocZhiduCons.uploadPath) + "/"+bo.getName());
FileInputStream f = new FileInputStream(file);
byte[] fb = new byte[f.available()];
f.read(fb);
ServletActionContext.getResponse().setHeader("Content-disposition",
"attachment; filename=" + new String(bo.getName().getBytes("gb2312"), "iso8859-1"));
ByteArrayInputStream bais = new ByteArrayInputStream(fb);
int b;
while ((b = bais.read()) != -1)
{
ServletActionContext.getResponse().getOutputStream().write(b);
}
ServletActionContext.getResponse().getOutputStream().flush();
}


如果文件不存在时,可能会报错,上面是将异常抛出,下面代码作一简单改造,自已捕获异常并返回错误信息。

public String downLoad(String id)
{
DocZhidu bo=(DocZhidu)dao.getObjectById(DocZhidu.class, id);
File file = new File(ServletActionContext.getServletContext().getRealPath(DocZhiduCons.uploadPath) + "/"+bo.getName());
String info=null;
try {
FileInputStream f = new FileInputStream(file);
byte[] fb = new byte[f.available()];
f.read(fb);
ServletActionContext.getResponse().setHeader("Content-disposition",
"attachment; filename=" + new String(bo.getName().getBytes("gb2312"), "iso8859-1"));
ByteArrayInputStream bais = new ByteArrayInputStream(fb);
int b;
while ((b = bais.read()) != -1)
{
ServletActionContext.getResponse().getOutputStream().write(b);
}
ServletActionContext.getResponse().getOutputStream().flush();
}
catch (IOException e)
{
info="下载的文件不存在,可能已被删除!";
}
return info;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值