java实现文件的断点续传和断点下载,有知道的交流下。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java实现文件的断点续传和断点下载,有知道的交流下。相关的知识,希望对你有一定的参考价值。
java实现文件的断点续传和断点下载,有知道的交流下。
参考技术A- /** * 下载服务器已存在的文件 * * @param request * @param response * @param proposeFile * @throws IOException * @throws FileNotFoundException */ private void downloadExistsFile(HttpServletRequest request, HttpServletResponse response, File proposeFile) throws IOException, FileNotFoundException log.debug("下载文件路径:" + proposeFile.getPath()); long fSize = proposeFile.length(); // 下载 response.setContentType("application/x-download"); String isoFileName = this .encodeFilename(proposeFile.getName(), request); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Length", String.valueOf(fSize)); response.setHeader("Content-Disposition", "attachment; filename=" + isoFileName); long pos = 0; if (null != request.getHeader("Range")) // 断点续传 response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); try pos = Long.parseLong(request.getHeader("Range").replaceAll( "bytes=", "").replaceAll("-", "")); catch (NumberFormatException e) log.error(request.getHeader("Range") + " is not Number!"); pos = 0; ServletOutputStream out = response.getOutputStream(); BufferedOutputStream bufferOut = new BufferedOutputStream(out); InputStream inputStream = new FileInputStream(proposeFile); String contentRange = new StringBuffer("bytes ").append( new Long(pos).toString()).append("-").append( new Long(fSize - 1).toString()).append("/").append( new Long(fSize).toString()).toString(); response.setHeader("Content-Range", contentRange); log.debug("Content-Range", contentRange); inputStream.skip(pos); byte[] buffer = new byte[5 * 1024]; int length = 0; while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) bufferOut.write(buffer, 0, length); bufferOut.flush(); bufferOut.close(); out.close(); inputStream.close();
你这个好像是断点下载的,上传的有吗
参考技术B我项目中用到的关键代码,断点下载文件:
URL url = new URL("http://f1.market.xiaomi.com/download/AppStore/0279e54e42c95454b29ac9628eccb1bfb5be22aeb/dian.zi.com.zidian.apk");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("User-Agent", "NetFox");
httpConnection.setReadTimeout(60000);
//xxx表示你已下载的文件大小
httpConnection.setRequestProperty("RANGE", "bytes=" + xxx + "-");
以上是关于java实现文件的断点续传和断点下载,有知道的交流下。的主要内容,如果未能解决你的问题,请参考以下文章
Unity 使用UnityWebRequest下载超大资源,实现断点续传和分段下载。