在网页编程时,文件下载,有一种方法就是用超链接直接指向文件所在路径(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;
}