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;
    }
}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值