vue+java实现大文件上传解决方案


分片上传大文件Demo

为了实现分片上传,包括断点续传和重试机制,我们可以使用Vue.js作为前端,Spring Boot作为后端。这个方案包括以下步骤:

  1. 前端:

    • 使用Vue.js进行文件分片上传。
    • 管理分片上传的进度和状态,处理断点续传和重试。
  2. 后端:

    • 使用Spring Boot处理分片上传的请求。
    • 存储上传的分片并重组成完整的文件。

前端(Vue.js)

首先,安装所需的依赖项,例如axios(用于发送HTTP请求)。

npm install axios

然后,编写一个Vue组件来处理分片上传:

<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="uploadFile" :disabled="!file">Upload</button>
    <div v-if="uploadProgress >= 0">Upload Progress: {{ uploadProgress }}%</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
      chunkSize: 2 * 1024 * 1024, // 2MB
      uploadProgress: -1
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
    },
    async uploadFile() {
      if (!this.file) return;

      const totalChunks = Math.ceil(this.file.size / this.chunkSize);
      let uploadedChunks = 0;

      for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
        const start = chunkIndex * this.chunkSize;
        const end = Math.min(this.file.size, start + this.chunkSize);
        const chunk = this.file.slice(start, end);

        const formData = new FormData();
        formData.append('file', chunk);
        formData.append('fileName', this.file.name);
        formData.append('chunkIndex', chunkIndex);
        formData.append('totalChunks', totalChunks);

        await this.uploadChunk(formData, chunkIndex);

        uploadedChunks++;
        this.uploadProgress = Math.floor((uploadedChunks / totalChunks) * 100);
      }

      alert('File upload completed!');
    },
    async uploadChunk(formData, chunkIndex) {
      try {
        await axios.post('/upload', formData);
      } catch (error) {
        console.error(`Failed to upload chunk ${chunkIndex}`, error);
        // Retry logic here
        await this.uploadChunk(formData, chunkIndex);
      }
    }
  }
};
</script>

后端(Spring Boot)

创建一个Spring Boot应用程序,并编写一个Controller来处理文件上传请求:

pom.xml

首先,确保你有以下依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

FileUploadController.java

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.util.concurrent.ConcurrentHashMap;

@RestController
public class FileUploadController {

    private static final String UPLOAD_DIR = "uploads/";
    private ConcurrentHashMap<String, Integer> uploadedChunks = new ConcurrentHashMap<>();

    @PostMapping("/upload")
    public void uploadFile(@RequestParam("file") MultipartFile file,
                           @RequestParam("fileName") String fileName,
                           @RequestParam("chunkIndex") int chunkIndex,
                           @RequestParam("totalChunks") int totalChunks) throws IOException {
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        File tempFile = new File(UPLOAD_DIR + fileName + ".part" + chunkIndex);
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.write(file.getBytes());
        }

        // Track uploaded chunks
        uploadedChunks.put(fileName + chunkIndex, chunkIndex);

        // If all chunks are uploaded, combine them
        if (uploadedChunks.size() == totalChunks) {
            combineChunks(fileName, totalChunks);
            uploadedChunks.clear();
        }
    }

    private void combineChunks(String fileName, int totalChunks) throws IOException {
        File finalFile = new File(UPLOAD_DIR + fileName);
        try (FileOutputStream fos = new FileOutputStream(finalFile, true)) {
            for (int i = 0; i < totalChunks; i++) {
                File partFile = new File(UPLOAD_DIR + fileName + ".part" + i);
                fos.write(java.nio.file.Files.readAllBytes(partFile.toPath()));
                partFile.delete();
            }
        }
    }
}

总结

这段代码实现了一个分片上传文件的系统,包括断点续传和重试机制。前端使用Vue.js来处理文件分片并上传,后端使用Spring Boot来接收并重组文件。你可以根据需要进一步扩展和优化这些代码,例如添加更多的错误处理和日志记录。


  • 31
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

饼干饿死了

三连和打赏总要留一个吧

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

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

打赏作者

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

抵扣说明:

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

余额充值