java文件下载断点续传

public static void outputFile(HttpServletResponse response,
HttpServletRequest request, 
String fileName, 
InputStream is,
long fileSize) throws FileNotFoundException,UnsupportedEncodingException, IOException {
response.setContentType("application/octet-stream");
javax.servlet.ServletOutputStream outputStream = response.getOutputStream();
String range = request.getHeader("RANGE");
long p = 0;
// tell the client to allow accept-ranges
response.reset();
response.setHeader("Accept-Ranges", "bytes");
// client requests a file block download start byte
if (range != null) {
response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
p = Long.parseLong(range.replaceAll("bytes=", "").replaceAll("-",""));
}
// response.setHeader("Content-Length", new Long(fileSize).toString());
response.setHeader("Content-Length", new Long(fileSize - p).toString());
response.setHeader("Content-Disposition", "attachment; filename=\""
+ java.net.URLEncoder.encode(fileName, "UTF-8") + "\"");
if (p != 0) {
// 断点开始
// 响应的格式是:
// Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]
String contentRange = new StringBuffer("bytes ")
.append(new Long(p).toString()).append("-")
.append(new Long(fileSize - 1).toString()).append("/")
.append(new Long(fileSize).toString()).toString();
response.setHeader("Content-Range", contentRange);
// pointer move to seek
is.skip(p);
}
try {
if (is != null) {
byte[] buf = new byte[1024];
int num = 0;
while ((num = is.read(buf)) != -1) {
outputStream.write(buf, 0, num);
outputStream.flush();
}
}
} catch (IOException e) {
logger.error(e.toString());
} finally {
if (null != is) {
is.close();
is = null;
}
if (null != outputStream) {
outputStream.close();
outputStream = null;
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值