1. 程式人生 > >java檔案下載斷點續傳

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