当前位置: 首页 > article >正文

Java+Vue 断点续传功能实现

实现断点续传功能通常涉及前后端的协同工作。前端负责文件的分片上传和状态管理,后端负责接收文件分片并进行合并。下面是一个简单的示例,展示如何使用Java和Vue来实现断点续传功能。

前端(Vue)


1. 安装依赖


首先,确保你的Vue项目中安装了axios用于HTTP请求:

npm install axios

2. 创建文件上传组件


创建一个Vue组件来处理文件上传和断点续传逻辑:

<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="uploadFile">Upload</button>
    <button @click="pauseUpload">Pause</button>
    <button @click="resumeUpload">Resume</button>
    <div v-if="progress > 0">Progress: {{ progress }}%</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
      chunks: [],
      chunkSize: 1024 * 1024, // 1MB
      currentChunk: 0,
      progress: 0,
      paused: false,
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
      this.chunks = this.createChunks(this.file);
      this.currentChunk = 0;
      this.progress = 0;
      this.paused = false;
    },
    createChunks(file) {
      const chunks = [];
      const totalChunks = Math.ceil(file.size / this.chunkSize);

      for (let i = 0; i < totalChunks; i++) {
        const start = i * this.chunkSize;
        const end = Math.min(file.size, start + this.chunkSize);
        chunks.push(file.slice(start, end));
      }

      return chunks;
    },
    async uploadFile() {
      if (!this.file) {
        alert('Please select a file first.');
        return;
      }

      for (; this.currentChunk < this.chunks.length; this.currentChunk++) {
        if (this.paused) {
          break;
        }

        const formData = new FormData();
        formData.append('file', this.chunks[this.currentChunk]);
        formData.append('chunkNumber', this.currentChunk);
        formData.append('totalChunks', this.chunks.length);
        formData.append('fileName', this.file.name);

        try {
          await axios.post('/api/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
            },
            onUploadProgress: (progressEvent) => {
              const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              this.progress = ((this.currentChunk * 100) / this.chunks.length) + (percentCompleted / this.chunks.length);
            },
          });
        } catch (error) {
          console.error('Upload failed:', error);
          break;
        }
      }

      if (this.currentChunk === this.chunks.length) {
        alert('File uploaded successfully!');
      }
    },
    pauseUpload() {
      this.paused = true;
    },
    resumeUpload() {
      this.paused = false;
      this.uploadFile();
    },
  },
};
</script>

后端(Java)


1. 添加依赖


确保你的Spring Boot项目中添加了以下依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.11.0</version>
    </dependency>
</dependencies>

2. 创建文件上传控制器


创建一个控制器来处理文件分片上传和合并:

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class FileUploadController {

    private static final String UPLOAD_DIR = "uploads/";

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file,
                             @RequestParam("chunkNumber") int chunkNumber,
                             @RequestParam("totalChunks") int totalChunks,
                             @RequestParam("fileName") String fileName,
                             HttpServletRequest request) throws IOException {
        String tempDir = UPLOAD_DIR + UUID.randomUUID().toString() + "/";
        Path tempPath = Paths.get(tempDir);
        if (!Files.exists(tempPath)) {
            Files.createDirectories(tempPath);
        }

        String chunkFileName = fileName + ".part" + chunkNumber;
        File chunkFile = new File(tempDir + chunkFileName);
        file.transferTo(chunkFile);

        if (chunkNumber == totalChunks - 1) {
            mergeChunks(tempDir, fileName, totalChunks);
            FileUtils.deleteDirectory(new File(tempDir));
        }

        return "Chunk uploaded successfully";
    }

    private void mergeChunks(String tempDir, String fileName, int totalChunks) throws IOException {
        File outputFile = new File(UPLOAD_DIR + fileName);
        for (int i = 0; i < totalChunks; i++) {
            File chunkFile = new File(tempDir + fileName + ".part" + i);
            FileUtils.copyFile(chunkFile, outputFile, true);
            chunkFile.delete();
        }
    }
}

3. 配置文件


确保在application.properties中配置文件上传的大小限制:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

4. 运行项目


启动Spring Boot应用和Vue前端应用,然后尝试上传一个大文件,测试断点续传功能。


总结


通过上述步骤,你可以在Java后端和Vue前端之间实现一个简单的断点续传功能。前端负责文件的分片上传和状态管理,后端负责接收文件分片并进行合并。希望这个示例对你有所帮助!


http://www.kler.cn/a/454382.html

相关文章:

  • 【Java 数据结构】链表的中间结点
  • 【华为OD-E卷-租车骑绿道 100分(python、java、c++、js、c)】
  • C++ 最小栈 - 力扣(LeetCode)
  • 杂项记录一些笔记
  • linux服务器上CentOS的yum和Ubuntu包管理工具apt区别与使用实战
  • AIOps平台的功能对比:如何选择适合的解决方案?
  • 简单贪吃蛇小游戏的设计与实现
  • es创建的索引状态一直是red
  • Effective C++ 条款 09:绝不在构造和析构过程中调用 virtual 函数
  • python操作Elasticsearch执行增删改查
  • 十二月第23讲:.NET 9 New features-AOT相关的改进
  • ubuntu搭建redis cluster集群三主三从(从0搭建,小白也会,不啰嗦)
  • (十)Ubuntu 20.04+akiaaa大神 Stable Diffusion整合包 AI绘画教程-外挂VAE模型等快捷设置教程
  • HarmonyOS NEXT 实战之元服务:静态案例效果---电动车电池健康状况
  • DPO(Direct Preference Optimization)算法解释:中英双语
  • 嵌入式学习-QT-Day11
  • .NET Core 中使用 C# 获取Windows 和 Linux 环境兼容路径合并
  • springcloud依赖
  • MongoDB 创建用户、User、Role 相关 操作
  • 机器学习基础算法 (二)-逻辑回归