Java 断点续传

最下方附项目地址

依赖

<dependency>
    <groupId>cn.novelweb</groupId>
    <artifactId>tool-core</artifactId>
    <version>1.3.22</version>
</dependency>

前端使用  WebUploader

上传接口

public interface BreakingPointUploadService {

    /**
     * 小文件上传
     *
     * @param file 文件
     * @return {@link Result}<{@link String}>
     */
    AjaxResult uploadFiles(MultipartFile file);

    /**
     * 检查文件MD5
     *
     * @param md5      md5
     * @param fileName 文件名称
     * @return {@link Result}<{@link Object}>
     */
    AjaxResult checkFileMd5(String md5, String fileName);

    /**
     * 断点续传
     *
     * @param param   参数
     * @param request 请求
     * @return {@link Result}<{@link Object}>
     */
    AjaxResult breakpointResumeUpload(UploadFileParam param, HttpServletRequest request);

}

接口实现

@Slf4j
@Service
public class BreakingPointUploadServiceImpl implements BreakingPointUploadService {


    @Override
    public AjaxResult uploadFiles(MultipartFile file) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            String fileName = file.getOriginalFilename();
            // 文件名非空校验
            if (StringUtils.isBlank(fileName)) {
                return AjaxResult.error("文件名不能为空");
            }
            // 大文件判定
            if (file.getSize() > SysConstant.MAX_SIZE) {
                return AjaxResult.error("文件过大,请使用大文件传输");
            }
            // 重命名文件
            File newFile = new File("E:/upload", fileName);
            // 如果该存储路径不存在则新建存储路径
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            // 文件写入
            file.transferTo(newFile);
            return AjaxResult.success("上传完成");
        } catch (Exception e) {
            log.error("上传协议文件出错", e);
            return AjaxResult.error("上传协议文件出错");
        }
    }

    @Override
    public AjaxResult checkFileMd5(String md5, String fileName) {
        try {
            cn.novelweb.tool.http.Result result = LocalUpload.checkFileMd5(md5, fileName, "E:/breakpoint", "E:/upload");
            return NovelWebUtils.forReturn(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return AjaxResult.error("上传失败");
    }

    @Override
    public AjaxResult breakpointResumeUpload(UploadFileParam param, HttpServletRequest request) {
        try {
            // 这里的 chunkSize(分片大小) 要与前端传过来的大小一致   webuploader默认5M。 这里直接使用默认值
            cn.novelweb.tool.http.Result result = LocalUpload.fragmentFileUploader(param, "E:/breakpoint", "E:/upload", 5242880L, request);
            return NovelWebUtils.forReturn(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return AjaxResult.error("上传失败");
    }
}

上传页面

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <link th:href="@{/css/break-point.css}" rel="stylesheet"/>
    <script th:src="@{/js/lib/jquery-3.3.1.min.js}"></script>
    <script th:src="@{/js/constant/urls.js}"></script>
    <script th:src="@{/js/constant/SysConstent.js}"></script>
    <script th:src="@{/js/lib/web-uploader.min-0.1.6.js}"></script>
    <script th:src="@{/js/lib/uploader.js}"></script>
    <script th:src="@{/js/page/break-point.js}"></script>
    <script th:src="@{/js/utils/line-background.js}"></script>
</head>
<body>
<div class="main">
    <div class="file-list" id="fileList">
        <ul>
            <li class="fl-li" id="addFile"><img th:src="@{/img/add.png}"><label>添加文件</label></li>
        </ul>
    </div>
    <!-- 上传进度 -->
    <div class="upload-progress" id="uploadProgress">
        <img id="up-spread" th:src="@{/img/up.png}"/>
        <div class="up-content">
            <ul class="upc-data" id="upcData"></ul>
        </div>
    </div>
</div>
</body>
</html>

演示截图

 
项目地址https://gitee.com/xn-mg/breakpoint-continuation

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java 断点的代码实现可以分为以下几步: 1. 记录文件已经下载的长度 2. 设置 HTTP 请求头中 "Range" 字段,告诉服务器从文件的哪个位置开始下载 3. 使用 Java I/O 流下载文件 4. 保存文件已经下载的长度,以便下次继下载 以下是一个简单的 Java 代码示例: ``` import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class Downloader { private static final int BUFFER_SIZE = 4096; public static void downloadFile(String fileURL, String saveDir) throws IOException { URL url = new URL(fileURL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); // 检查 HTTP 响应码 if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String disposition = httpConn.getHeaderField("Content-Disposition"); String contentType = httpConn.getContentType(); int contentLength = httpConn.getContentLength(); if (disposition != null) { // 检索文件名 int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { // 检索文件名 fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); } System.out.println("Content-Type = " + contentType); System.out.println("Content-Disposition = " + disposition); System.out.println("Content-Length = " + contentLength); System.out.println("fileName = " + fileName); // 打开本地文件输出流 OutputStream outputStream = new FileOutputStream(saveDir + File.separator + fileName); // 打开网络输入流 InputStream inputStream = httpConn.getInputStream(); int bytesRead = -1; byte[] buffer = new byte[BUFFER_SIZE]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0 ### 回答2: 断点是指在文件输过程中,当输中断时,重新开始输时能够从中断点输,而不是重新开始。下面给出一个使用 Java 实现断点的简单示例代码。 ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class ResumeDownload { public static void main(String[] args) { String fileUrl = "http://example.com/file.zip"; // 需要下载的文件地址 String savePath = "C:/Downloads/file.zip"; // 文件保存路径 try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); File file = new File(savePath); long downloaded = 0; // 已下载的文件大小 if (file.exists()) { downloaded = file.length(); connection.setRequestProperty("Range", "bytes=" + downloaded + "-"); } connection.connect(); FileOutputStream outputStream = new FileOutputStream(file, true); // 追加写入模式 InputStream inputStream = connection.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead; long totalDownloaded = downloaded; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); totalDownloaded += bytesRead; } outputStream.close(); inputStream.close(); System.out.println("文件下载完成!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码中,通过使用 HttpURLConnection 进行文件下载。首先检查文件是否存在,若存在则设置请求头 Range 属性为已下载文件的大小,从断点处开始下载。然后将文件输入流写入到文件输出流中,实现断点。 ### 回答3: Java断点代码主要通过处理文件的读写来实现。下面是一个简单的实现示例: ```java import java.io.*; public class ResumableFileDownloader { private static final int BUFFER_SIZE = 1024; public static void resumeDownload(String url, String filePath, long resumePosition) throws IOException { BufferedInputStream in = null; RandomAccessFile file = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Range", "bytes=" + resumePosition + "-"); in = new BufferedInputStream(conn.getInputStream()); file = new RandomAccessFile(filePath, "rw"); file.seek(resumePosition); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { file.write(buffer, 0, bytesRead); } } finally { if (in != null) { in.close(); } if (file != null) { file.close(); } } } public static void main(String[] args) { try { long resumePosition = 0; // 设置的起始位置 resumeDownload("http://example.com/file.pdf", "downloaded_file.pdf", resumePosition); } catch (IOException e) { e.printStackTrace(); } } } ``` 在该代码中,`resumeDownload`方法接收一个URL、文件保存路径和的起始位置作为参数。它首先从指定位置发起HTTP请求,设置`Range`头部以指定从该位置开始下载。然后通过`BufferedInputStream`读取数据,并通过`RandomAccessFile`写入文件,同时更新写入的位置。通过设置`RandomAccessFile`的`seek`方法,我们可以指定写入文件的位置。 在`main`方法中,我们可以设置的起始位置并调用`resumeDownload`方法来执行断点。例如,我们可以将文件下载到`downloaded_file.pdf`的位置,并从上一次未下载完成的位置继下载。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值