java文件下载断点续传

来源:互联网 发布:java和php哪个更累 编辑:程序博客网 时间:2024/05/29 07:47
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;
}
}
}
0 0