断点续传下载
程序员文章站
2022-04-10 22:52:43
...
最近写的一个断点下载功能代码,支持迅雷,旋风,IE等下载。迅雷、旋风测试正常,代码如下:
request.setCharacterEncoding("UTF-8"); String primary = request.getParameter("primary"); String uid = request.getParameter("uid"); String timestamp = request.getParameter("timestamp"); String verify = request.getParameter("verify"); //校验下载权限 String verify_n = MD5.md5(uid + primary + "lyjilu" + timestamp); if (!verify_n.equals(verify)) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } response.reset(); String filePath = ZipAssist.getZipPath(primary); File file = new File(filePath); if(!file.exists() || !file.isFile()){ response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String range = request.getHeader("range"); long fileLen = file.length(); long begin = 0; long end = fileLen - 1; String contentRange = null; if (range != null) { //设置状态 response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); //得到请求byte范围 String rangeBytes = range.replace("bytes=", ""); String[] rangeArr = rangeBytes.trim().split("-"); begin = Long.parseLong(rangeArr[0]); // 如果请求有结束范围 eg:1024000-2058220 if (rangeArr.length > 1) { end = Long.parseLong(rangeArr[1]); } contentRange = new StringBuffer("bytes ").append(begin).append("-") .append(end).append("/").append(fileLen).toString(); } // 设置响应信息 response.setContentType("application/octet-stream; charset=utf-8"); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Range", contentRange); request.setCharacterEncoding("UTF-8"); response.addHeader( "Content-Disposition", "attachment;filename=" + new String(filePath.substring( filePath.lastIndexOf(File.separator) + 1) .getBytes("gb2312"), "ISO8859-1")); response.addHeader("Content-Length", String.valueOf(end + 1 - begin)); ServletOutputStream out = null; RandomAccessFile randomf = null; try { randomf = new RandomAccessFile(file, "r"); out = response.getOutputStream(); byte[] bt = new byte[1024 * 1024]; int i = -1; try { // 读取数据 randomf.seek(begin); while ((i = randomf.read(bt)) != -1) { if (randomf.getFilePointer() >= end) { out.write(bt, 0, (int) (i + end - randomf.getFilePointer() + 1)); break; } else out.write(bt, 0, i); } out.flush(); } catch (Exception e) { System.out.println("下载报错:" + e.toString()); } } catch (Exception e) { e.printStackTrace(); } finally { try { randomf.close(); } catch (Exception e) { } if (out != null) out.close(); } }
只支持:请求range为
1:null
2:xxxxxxx-
3:xxxxxxx-yyyyyyyyy
上一篇: 下拉菜单如何关联阿。()
下一篇: PHP 类型转换有关问题