实现断点续传功能通常涉及前后端的协同工作。前端负责文件的分片上传和状态管理,后端负责接收文件分片并进行合并。下面是一个简单的示例,展示如何使用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, // 1MBcurrentChunk: 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. 创建文件上传控制器
创建一个控制器来处理文件分片上传和合并:
java">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前端之间实现一个简单的断点续传功能。前端负责文件的分片上传和状态管理,后端负责接收文件分片并进行合并。希望这个示例对你有所帮助!