远程文件下载

HttpServletResponse response = ServletActionContext.getResponse();
InputStream input = null;
BufferedOutputStream bos = null;
long pos = 0l;
long endPos = 0l;
long length = 0l;
File file = null;
String realPath = ServletActionContext.getRequest().getRealPath("/attachment");
String xlsName="指数报告.xls";
String templatePath=realPath + "/" + xlsName;
try {
file = new File(templatePath);
response.setContentType("application/x-msdownload;charset=UTF-8");
response.setHeader("Content-disposition", "attachment; filename="
+ java.net.URLEncoder.encode(file.getName(), "UTF-8"));
if (file != null && file.exists() && file.isFile()) {
input = new FileInputStream(file);
length = file.length();
if (endPos == 0) {
endPos = length - 1;
}
} else {
LOGGER.debug("文件不存在:" + file.getAbsolutePath());
}
response.reset();
response.setHeader("Accept-Ranges", "bytes");
response.setContentType("application/x-msdownload;charset=UTF-8");
response.setHeader("Content-disposition", "attachment; filename="
+ java.net.URLEncoder.encode(file.getName(), "UTF-8"));
bos = new java.io.BufferedOutputStream(response.getOutputStream());
byte[] b = new byte[1024];
int len = 0;
if (pos != 0) {
String contentRange = new StringBuffer("bytes ")
.append(new Long(pos).toString()).append("-")
.append(new Long(endPos).toString()).append("/")
.append(new Long(length).toString()).toString();
response.setHeader("Content-Range", contentRange);
LOGGER.debug("Content-Range=" + contentRange);
// 略过已经传输过的字节
input.skip(pos);
}
response.setContentLength(Integer.valueOf((endPos + 1 - pos) + ""));
while ((len = input.read(b)) != -1) {// 9861632-9882111/9882112
pos = pos + len - 1;
if (pos > endPos) {
bos.write(b, 0, (int) (len - (pos - endPos)));
bos.flush();
break;
} else {
bos.write(b, 0, len);
bos.flush();
}
}
} catch (Exception ex) {
LOGGER.error("下载文件:" + templatePath + ",失败" + ex.getMessage());
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e) {
LOGGER.error("关闭输入流失败", e);
}
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
LOGGER.error("关闭输入流失败", e);
}


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值