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

}

虽然所给引用中未直接提及使用 JavaVue3、TypeScript 和 ElementPlus 实现文件分片上传到 OSS 的具体方案,但可以结合通用知识给出一个大致的实现思路。 ### 前端(Vue3、TypeScript、ElementPlus) #### 1. 安装依赖 使用以下命令初始化项目并安装所需依赖: ```bash npm init vite@latest my-file-upload-project -- --template vue-ts cd my-file-upload-project npm install element-plus ``` #### 2. 创建文件分片上传组件 利用 ElementPlus 的 `el-upload` 组件实现文件选择,然后在前端将文件进行分片。 ```vue <template> <el-upload ref="uploadRef" :action="uploadUrl" :headers="headers" :before-upload="handleBeforeUpload" :http-request="customRequest" :auto-upload="false" accept=".jpg,.png,.pdf" > <el-button type="primary">选择文件</el-button> </el-upload> </template> <script lang="ts" setup> import { ref } from 'vue'; import { ElMessage } from 'element-plus'; const uploadRef = ref(null); const uploadUrl = 'your-backend-api-url'; const headers = { 'Content-Type': 'application/json' }; const handleBeforeUpload = (file: File) => { const chunkSize = 1024 * 1024; // 1MB 分片大小 const fileSize = file.size; const chunkCount = Math.ceil(fileSize / chunkSize); for (let i = 0; i < chunkCount; i++) { const start = i * chunkSize; const end = Math.min(start + chunkSize, fileSize); const chunk = file.slice(start, end); // 发送分片数据到后端 const formData = new FormData(); formData.append('chunk', chunk); formData.append('chunkIndex', i.toString()); formData.append('totalChunks', chunkCount.toString()); formData.append('fileName', file.name); // 调用自定义上传方法 customRequest({ url: uploadUrl, data: formData, headers: headers }); } return false; // 阻止默认上传 }; const customRequest = (options: any) => { fetch(options.url, { method: 'POST', headers: options.headers, body: options.data }) .then(response => { if (response.ok) { ElMessage.success('分片上传成功'); } else { ElMessage.error('分片上传失败'); } }) .catch(error => { ElMessage.error('网络错误'); }); }; </script> ``` ### 后端(Java) #### 1. 创建 Spring Boot 项目 可以使用 Spring Initializr 或 Spring Tool Suite 创建一个 Spring Boot 项目,并添加必要的依赖,如 Spring Web、阿里云 OSS SDK 等。 #### 2. 编写文件分片接收和合并逻辑 ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; @RestController public class FileUploadController { private static final String TEMP_DIR = "temp/"; private static final String OSS_BUCKET_NAME = "your-oss-bucket-name"; @PostMapping("/upload") public String uploadChunk(@RequestParam("chunk") MultipartFile chunk, @RequestParam("chunkIndex") int chunkIndex, @RequestParam("totalChunks") int totalChunks, @RequestParam("fileName") String fileName) { try { // 保存分片到临时目录 File tempDir = new File(TEMP_DIR); if (!tempDir.exists()) { tempDir.mkdirs(); } File tempFile = new File(TEMP_DIR + fileName + ".part" + chunkIndex); try (FileOutputStream fos = new FileOutputStream(tempFile)) { fos.write(chunk.getBytes()); } // 检查是否所有分片都已上传 if (chunkIndex == totalChunks - 1) { mergeChunks(fileName, totalChunks); } return "Chunk uploaded successfully"; } catch (IOException e) { e.printStackTrace(); return "Error uploading chunk"; } } private void mergeChunks(String fileName, int totalChunks) throws IOException { List<File> chunks = new ArrayList<>(); for (int i = 0; i < totalChunks; i++) { chunks.add(new File(TEMP_DIR + fileName + ".part" + i)); } File mergedFile = new File(TEMP_DIR + fileName); try (FileOutputStream fos = new FileOutputStream(mergedFile)) { for (File chunk : chunks) { try (java.io.FileInputStream fis = new java.io.FileInputStream(chunk)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } } } } // 上传合并后的文件到 OSS uploadToOSS(mergedFile); // 删除临时文件 for (File chunk : chunks) { chunk.delete(); } mergedFile.delete(); } private void uploadToOSS(File file) { // 使用阿里云 OSS SDK 上传文件到 OSS // 示例代码省略,需要配置 OSS 客户端和相关参数 } } ``` ### 总结 上述代码实现了使用 JavaVue3、TypeScript 和 ElementPlus 进行文件分片上传到 OSS 的基本功能。前端负责文件选择和分片,后端负责接收分片、合并分片上传到 OSS。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值