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();
}
}