java web 文件下载代码_JavaWeb文件下载功能实例代码

在工作中遇到的一个下载文件的功能,自己将其抽取出来,代码简单,希望能帮到大家,好了,话不多说,上代码!

public void downloadFile(File file, String downName, HttpServletRequest request, HttpServletResponse response) {

OutputStream out = null;

FileInputStream fin = null;

BufferedInputStream bin = null;

try {

if (file.exists()) {

String finalFileName = null;

String agent = request.getHeader("User-Agent");

boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);

if (isMSIE) {

finalFileName = URLEncoder.encode(downName, "UTF8");

} else {

finalFileName = new String(downName.getBytes("UTF-8"), "ISO-8859-1");

}

response.setContentType("application/x-msdownload");

response.setHeader("Content-Disposition", "attachment; filename=".concat(finalFileName));

out = response.getOutputStream();

fin = new FileInputStream(file);

bin = new BufferedInputStream(fin);

for (int data = bin.read(); data > -1; data = bin.read()) {

out.write(data);

}

} else {

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (bin != null)

bin.close();

if (fin != null)

fin.close();

if (out != null)

out.close();

} catch (Exception e2) {

e2.printStackTrace();

}

}

}

以上就是本文JavaWeb文件下载的代码,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值