JAVA+VUE实现文件分片上传

<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="uploadFile">上传</button>
    <div v-if="progress">上传进度:{{ progress }}%</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
      chunkSize: 1 * 1024 * 1024, // 1MB
      progress: 0,
      uploadedChunks: 0,
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
      this.checkUploadedChunks();
    },
    async checkUploadedChunks() {
      if (!this.file) return;

      // 请求已上传的分片信息
      try {
        const response = await axios.get(`/upload/check?fileName=${this.file.name}`);
        this.uploadedChunks = response.data.uploadedChunks; // 已上传的分片数
      } catch (error) {
        console.error('获取已上传分片失败', error);
        this.uploadedChunks = 0;
      }
    },
    async uploadFile() {
      if (!this.file) return;

      const totalChunks = Math.ceil(this.file.size / this.chunkSize);
      const uploadPromises = [];

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

        const formData = new FormData();
        formData.append('file', chunk);
        formData.append('chunkIndex', i);
        formData.append('totalChunks', totalChunks);
        formData.append('fileName', this.file.name);

        uploadPromises.push(
          axios.post('/upload', formData, {
            onUploadProgress: (progressEvent) => {
              const percentage = Math.round((progressEvent.loaded / progressEvent.total) * 100);
              this.progress = ((i + percentage / 100) / totalChunks) * 100;
            },
          })
        );
      }

      await Promise.all(uploadPromises);
      alert('文件上传完成!');
    },
  },
};
</script>

``
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping(“/upload”)
public class FileUploadController {

private static final String UPLOAD_DIR = "uploads/";

@GetMapping("/check")
public CheckResponse checkUploadedChunks(@RequestParam("fileName") String fileName) {
    File file = new File(UPLOAD_DIR + fileName);
    if (file.exists()) {
        // 计算已上传的分片数
        int chunkSize = 1 * 1024 * 1024; // 1MB
        int uploadedChunks = (int) (file.length() / chunkSize);
        return new CheckResponse(uploadedChunks);
    }
    return new CheckResponse(0);
}

@PostMapping
public String uploadChunk(@RequestParam("file") MultipartFile file,
                          @RequestParam("chunkIndex") int chunkIndex,
                          @RequestParam("totalChunks") int totalChunks,
                          @RequestParam("fileName") String fileName) throws IOException {
    // 创建文件存储目录
    File dir = new File(UPLOAD_DIR);
    if (!dir.exists()) {
        dir.mkdirs();
    }

    // 将分片写入临时文件
    File tempFile = new File(UPLOAD_DIR + fileName + ".part" + chunkIndex);
    try (OutputStream out = new FileOutputStream(tempFile)) {
        out.write(file.getBytes());
    }

    // 检查是否所有分片都已上传
    if (chunkIndex == totalChunks - 1) {
        mergeFiles(fileName, totalChunks);
    }

    return "Chunk uploaded successfully!";
}

private void mergeFiles(String fileName, int totalChunks) throws IOException {
    File mergedFile = new File(UPLOAD_DIR + fileName);
    try (OutputStream out = new FileOutputStream(mergedFile, true)) {
        for (int i = 0; i < totalChunks; i++) {
            File tempFile = new File(UPLOAD_DIR + fileName + ".part" + i);
            if (tempFile.exists()) {
                out.write(java.nio.file.Files.readAllBytes(tempFile.toPath()));
                tempFile.delete(); // 删除临时文件
            }
        }
    }
}

static class CheckResponse {
    private int uploadedChunks;

    public CheckResponse(int uploadedChunks) {
        this.uploadedChunks = uploadedChunks;
    }

    public int getUploadedChunks() {
        return uploadedChunks;
    }
}

}

### SpringBoot、Vue 和 MinIO 文件分片上传实现方案 #### 一、技术栈概述 SpringBoot 是一个用于快速构建 Java 应用程序的框架,提供了强大的 RESTful API 支持;Vue.js 是一种流行的前端框架,适合构建交互式的单页应用 (SPA);MinIO 则是一个高性能的对象存储服务,支持 Amazon S3 协议接口。三者结合可以高效完成文件分片上传的任务。 --- #### 二、核心概念说明 1. **分片上传原理**: 将大文件分割成多个较小的部分(即分片),逐一分片上传到服务器端后再合并为完整的文件[^1]。 2. **断点续传机制**: 如果某个分片上传失败,则仅需重新上传该部分而无需重复整个过程。 3. **秒传优化**: 对于已存在的相同文件,通过计算哈希值判断其唯一性并跳过实际传输流程。 --- #### 三、具体实现步骤 ##### 1. 后端配置 (SpringBoot + MinIO) 在 SpringBoot 中集成 MinIO 客户端库 `minio-java` 来管理对象存储资源。 ###### Maven依赖引入 ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.5.7</version> </dependency> ``` ###### 配置类定义 创建 MinIO 的连接配置: ```java import io.minio.MinioClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MinioConfig { @Bean public MinioClient minioClient() { return MinioClient.builder() .endpoint("http://localhost:9000") // 替换为您的MinIO地址 .credentials("your-access-key", "your-secret-key") .build(); } } ``` ###### 分片上传逻辑 编写控制器处理分片请求: ```java @RestController @RequestMapping("/upload") public class FileUploadController { private final MinioClient minioClient; public FileUploadController(MinioClient minioClient) { this.minioClient = minioClient; } /** * 接收分片数据流 */ @PostMapping("/chunk/{fileName}/{index}") public ResponseEntity<String> uploadChunk(@PathVariable String fileName, @PathVariable int index, @RequestParam("file") MultipartFile filePart) throws Exception { try { InputStream inputStream = filePart.getInputStream(); // 构造目标路径名 String objectName = fileName + "_part_" + index; // 执行分片保存至MinIO minioClient.putObject( PutObjectArgs.builder() .bucket("my-bucket-name") // 存储桶名称 .object(objectName) .stream(inputStream, filePart.getSize(), -1) .contentType(filePart.getContentType()) .build()); return ResponseEntity.ok("成功上传第" + index + "个分片"); } catch (Exception e) { throw new RuntimeException(e); } } /** * 合并所有分片 */ @PostMapping("/merge/{fileName}") public ResponseEntity<String> mergeChunks(@PathVariable String fileName, @RequestBody List<Integer> chunkIndices) throws Exception { StringBuilder mergedContent = new StringBuilder(); for (int i : chunkIndices) { String partObjectName = fileName + "_part_" + i; // 获取每个分片的内容 GetObjectResponse response = minioClient.getObject( GetObjectArgs.builder().bucket("my-bucket-name").object(partObjectName).build()); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { mergedContent.append(line); } } // 创建最终的目标文件 minioClient.putObject(PutObjectArgs.builder() .bucket("my-bucket-name") .object(fileName) .stream(new ByteArrayInputStream(mergedContent.toString().getBytes()), -1, -1) .contentType("application/octet-stream") .build()); return ResponseEntity.ok("文件合并完成!"); } } ``` --- ##### 2. 前端设计 (Vue.js) 利用 Vue 实现文件切片与异步上传功能。 ###### HTML模板结构 ```html <div id="app"> <input type="file" @change="handleFileChange"/> <button @click="startUpload">开始上传</button> </div> ``` ###### JavaScript逻辑 ```javascript new Vue({ el: '#app', data: { selectedFile: null, chunkSize: 1024 * 1024 * 5, // 每个分片大小设为5MB uploadedChunks: [] }, methods: { handleFileChange(event) { this.selectedFile = event.target.files[0]; }, async startUpload() { const totalChunks = Math.ceil(this.selectedFile.size / this.chunkSize); for (let i = 0; i < totalChunks; i++) { const startByte = i * this.chunkSize; const endByte = Math.min(startByte + this.chunkSize, this.selectedFile.size); const chunkBlob = this.selectedFile.slice(startByte, endByte); await fetch(`/upload/chunk/${this.selectedFile.name}/${i}`, { method: 'POST', headers: { 'Content-Type': 'multipart/form-data' }, body: new FormData().append('file', chunkBlob), }); console.log(`已完成 ${i + 1} / ${totalChunks}`); this.uploadedChunks.push(i); } // 发送合并请求 await fetch('/upload/merge/' + this.selectedFile.name, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.uploadedChunks), }); } } }); ``` --- #### 四、注意事项 - 确保 MinIO 已经启动并且能够正常访问[^2]。 - 调整分片大小时应综合考虑网络环境和硬件性能[^3]。 - 使用 HTTPS 加密通信以保障敏感数据的安全性。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值