java 断点续传 服务端_java服务端下载断点续传功能实现

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

request.setCharacterEncoding("UTF-8");

String filename = request.getParameter("name");

String filePath = "D:/files/" + filename;

long startIndex = 0;

long endIndex = 0;

long fileSize = 0;

File f = new File(filePath);

InputStream is;

try {

is = new FileInputStream(f);

}catch(FileNotFoundException e) {

response.sendError(HttpServletResponse.SC_NOT_FOUND);    //404

return;

}

fileSize = f.length();

endIndex = fileSize-1;

String range = request.getHeader("Range");

if (range != null) {

range = range.trim();

if (range.matches("^(bytes=)\\d+(-)$")) {

String numRegex = "\\d+";

Pattern p = Pattern.compile(numRegex);

Matcher m = p.matcher(range);

if (m.find()) {

String numStr = range.substring(m.start(), m.end());

startIndex = Long.parseLong(numStr);

}

}else if (range.matches("^(bytes=)\\d+-(\\d+)$")) {

String numRegex = "\\d+";

Pattern p = Pattern.compile(numRegex);

Matcher m = p.matcher(range);

if (m.find()) {

String numStr = range.substring(m.start(), m.end());

startIndex = Long.parseLong(numStr);

}

if (m.find()) {

String numStr = range.substring(m.start(), m.end());

endIndex = Long.parseLong(numStr);

if (endIndex > fileSize-1) {

endIndex = fileSize-1;

}

}

}else{

response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); //416

return;

}

if (startIndex > endIndex) {

response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); //416

return;

}else{

response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);    //206

response.setHeader("Accept-Ranges", "bytes");

String contentRange = String.format("bytes %d-%d/%d", startIndex, endIndex, fileSize);

response.setHeader("Content-Range", contentRange);

}

}

//System.out.println("startIndex:" + startIndex + " end:" + endIndex);

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

response.setHeader("content-disposition", "attachment;filename=" + filename);

response.setContentLengthLong(endIndex-startIndex+1);

try {

ServletOutputStream out = response.getOutputStream();

if (startIndex != 0) {

is.skip(startIndex);

}

byte[] buf = new byte[1024];

int len = -1;

long currentIndex = startIndex;

//读1024的整数倍部分

while (currentIndex < (endIndex+1-1024)) {

len = is.read(buf);

currentIndex += len;

out.write(buf, 0, len);

}

//读取剩下的部分

if (currentIndex < endIndex) {

len = is.read(buf, 0, (int)(endIndex+1 - currentIndex));

out.write(buf, 0, len);

}

} catch (Exception e) {

response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); //500

}finally {

// TODO: handle finally clause

is.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值