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在后端保存文件。前端将文件分片并逐个上传到后端,后端接收到所有分片后再进行合并,最终保存为一个完整文件。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天天进步2015

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值