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

java实现文件下载 调用IE自带的下载工具来完成下载

2013-05-07 14:01 609 查看
/**

* @author

* May 7, 2013 1:56:03 PM

* @param path 下载文件的全路径(包括文件名)

* @param response

* @throws FileNullException 自定义异常,当前文件不存在的时候抛出此异常

* @throws IOException

*/

public static void download(String path, HttpServletResponse response) throws FileNullException, IOException {

OutputStream toClient = null;

InputStream bis = null;

FileInputStream fis = null;

// path是指欲下载的文件的路径。

File file = new File(path);

//判断当前文件是否存在,若是不存在则跑出异常

if(!file.exists()) {

throw new FileNullException("下载失败,该文件不存在,可能已经被删除");

}

// 取得文件名。

String filename = file.getName();

// 以流的形式下载文件。

fis = new FileInputStream(path);

bis = new BufferedInputStream(fis);

byte[] buffer = new byte[bis.available()];

fis.read(buffer);

fis.close();

bis.close();

// 清空response

response.reset();

// 设置response的Header

response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));

response.addHeader("Content-Length", "" + file.length());

toClient = new BufferedOutputStream(response.getOutputStream());

response.setContentType("application/octet-stream");

toClient.flush();

toClient.write(buffer);

toClient.close();

}

注意事项:我这里并没有抓取异常信息,而是将异常信息抛向了调用方(action)中,在action中进行了除了。FileNullException自定义异常,主要是用来抛出文件不存在的信息,用于在页面提示用户。当然也可以有其他处理方式,可自行实现。

由于csdn上传资源功能有问题,导致经常无法上传,顾我将不上传源代码。有意者可以留言索要。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: