Vue 3 和 SpringBoot 实现文件分片上传示例

前端实现(Vue 3和vue-upload-component)

  1. 安装 vue-upload-component
npm install vue-upload-component --save
  1. 创建一个Vue组件用于上传文件(FileUploader.vue):
<template>
  <div>
    <file-upload
      :multiple="false"
      :size="5242880"
      :thread="1"
      :auto="true"
      :extensions="['jpg', 'png', 'gif']"
      @input-file="inputFile"
      ref="upload"
    >
      <div class="btn btn-primary">选择文件</div>
    </file-upload>
  </div>
</template>

<script>
import FileUpload from 'vue-upload-component';

export default {
  components: {
    FileUpload,
  },
  data() {
    return {
      uploadUrl: '/upload',
      chunkSize: 1 * 1024 * 1024, // 1MB
    };
  },
  methods: {
    inputFile(newFile, oldFile, prevent) {
      if (newFile && newFile.file) {
        if (newFile.active && newFile.size > this.chunkSize) {
          prevent();
          this.uploadChunks(newFile);
        }
      }
    },
    async uploadChunks(file) {
      const totalChunks = Math.ceil(file.size / this.chunkSize);
      for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
        const start = chunkIndex * this.chunkSize;
        const end = Math.min(start + this.chunkSize, file.size);
        const chunk = file.file.slice(start, end);
        const formData = new FormData();
        formData.append('file', chunk);
        formData.append('chunk', chunkIndex + 1);
        formData.append('totalChunks', totalChunks);
        formData.append('fileName', file.name);
        
        await this.uploadChunk(formData);
      }
      // Notify backend that all chunks have been uploaded
      await this.uploadComplete(file);
    },
    uploadChunk(formData) {
      return fetch(this.uploadUrl, {
        method: 'POST',
        body: formData,
      }).then(response => response.json());
    },
    uploadComplete(file) {
      return fetch(\`\${this.uploadUrl}/complete\`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          fileName: file.name,
          totalChunks: Math.ceil(file.size / this.chunkSize),
        }),
      }).then(response => response.json());
    },
  },
};
</script>

后端实现(Spring Boot)

  1. 在Spring Boot项目中创建控制器:
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    private final Path rootLocation = Paths.get("upload-dir");

    @PostMapping
    public ResponseEntity<String> uploadChunk(
            @RequestParam("file") MultipartFile file,
            @RequestParam("chunk") int chunk,
            @RequestParam("totalChunks") int totalChunks,
            @RequestParam("fileName") String fileName) throws IOException {

        Files.createDirectories(rootLocation);

        Path tempFile = this.rootLocation.resolve(fileName + ".part" + chunk);
        Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

        return ResponseEntity.ok().body("Chunk " + chunk + " is uploaded successfully.");
    }

    @PostMapping("/complete")
    public ResponseEntity<String> completeUpload(@RequestBody CompleteUploadRequest request) throws IOException {

        Path targetFile = this.rootLocation.resolve(request.getFileName());

        try (OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
            for (int i = 1; i <= request.getTotalChunks(); i++) {
                Path tempFile = this.rootLocation.resolve(request.getFileName() + ".part" + i);
                Files.copy(Files.newInputStream(tempFile), os);
                Files.delete(tempFile);
            }
        }

        return ResponseEntity.ok().body("File uploaded and merged successfully.");
    }

    public static class CompleteUploadRequest {
        private String fileName;
        private int totalChunks;

        // Getters and setters
    }
}

以上代码展示了如何在Vue 3中使用vue-upload-component实现分片上传,并使用Spring Boot在后端保存文件。前端将文件分片并逐个上传到后端,后端接收到所有分片后再进行合并,最终保存为一个完整文件。

相关推荐

  1. Vue 3 SpringBoot 实现文件分片示例

    2024-07-22 16:52:02       17 阅读
  2. vue3+springboot+minio,实现文件功能

    2024-07-22 16:52:02       18 阅读
  3. vue3 文件分片

    2024-07-22 16:52:02       25 阅读
  4. vue3+ts实现文件

    2024-07-22 16:52:02       19 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 16:52:02       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 16:52:02       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 16:52:02       45 阅读
  4. Python语言-面向对象

    2024-07-22 16:52:02       55 阅读

热门阅读

  1. ElasticSearch-match_phrase查询

    2024-07-22 16:52:02       14 阅读
  2. 计算机视觉主流框架及其应用方向

    2024-07-22 16:52:02       21 阅读
  3. NLP基础技术

    2024-07-22 16:52:02       18 阅读
  4. Linux的shell编程

    2024-07-22 16:52:02       18 阅读
  5. 【Vue】 组件通信方式

    2024-07-22 16:52:02       13 阅读
  6. Android 各个版本兼容型问题

    2024-07-22 16:52:02       17 阅读
  7. 透彻理解Transformer模型:详解及实用示例(C#版)

    2024-07-22 16:52:02       16 阅读
  8. 商品信息管理系统(C语言)

    2024-07-22 16:52:02       16 阅读
  9. Vue的模板编译:深入理解渲染函数与预编译模板

    2024-07-22 16:52:02       16 阅读
  10. Rust编程- 函数指针与返回闭包

    2024-07-22 16:52:02       17 阅读