java下载实现_java 实现下载功能

/**

* 下载文件

* @param filePath --文件完整路径

* @param response --HttpServletResponse对象

*/

public static void downloadFile(

String filePath,

javax.servlet.http.HttpServletResponse response) {

String fileName = ""; //文件名,输出到用户的下载对话框

//从文件完整路径中提取文件名,并进行编码转换,防止不能正确显示中文名

try {

if(filePath.lastIndexOf("/") > 0) {

fileName = new String(filePath.substring(filePath.lastIndexOf("/")+1, filePath.length()).getBytes("GB2312"), "ISO8859_1");

}else if(filePath.lastIndexOf("\\") > 0) {

fileName = new String(filePath.substring(filePath.lastIndexOf("\\")+1, filePath.length()).getBytes("GB2312"), "ISO8859_1");

}

}catch(Exception e) {}

//打开指定文件的流信息

FileInputStream fs = null;

try {

fs = new FileInputStream(new File(filePath));

}catch(FileNotFoundException e) {

e.printStackTrace();

return;

}

//设置响应头和保存文件名

response.setContentType("APPLICATION/OCTET-STREAM");

response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

//写出流信息

int b = 0;

try {

PrintWriter out = response.getWriter();

while((b=fs.read())!=-1) {

out.write(b);

}

fs.close();

out.close();

System.out.println("文件下载完毕.");

}catch(Exception e) {

e.printStackTrace();

System.out.println("下载文件失败!");

}

}

方法在表现层里调用,比如Struts或Servlet里。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值