当前位置:   article > 正文

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

vue3 springboot分片上传

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

  1. 安装 vue-upload-component
npm install vue-upload-component --save
  • 1
  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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76

后端实现(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
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/872769
推荐阅读
相关标签
  

闽ICP备14008679号