首页 > 编程语言 >vue+java实现大文件上传解决方案

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

时间:2024-06-06 17:59:19浏览次数:23  
标签:vue java File formData fileName file totalChunks chunkIndex 上传


分片上传大文件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来接收并重组文件。你可以根据需要进一步扩展和优化这些代码,例如添加更多的错误处理和日志记录。


标签:vue,java,File,formData,fileName,file,totalChunks,chunkIndex,上传
From: https://blog.csdn.net/weixin_45408984/article/details/139506649

相关文章

  • 【忻州师范学院毕业论文】基于Java的家政公司网站的设计与实现
    注:仅展示部分文档内容和系统截图,需要完整的视频、代码、文章和安装调试环境请私信up主。1.1 开发背景及研究意义随着我国人口的增长、人们生活水平的提高,居民社会需求也随之增多,市场经济的快速发展和信息化水平的不断提高,人们的工作节奏也不断加快,许多人们没有闲暇的时间和......
  • vue 混入 mixins
    vue2写法mixins.jsimport{reactive}from"vue";exportconstmixins=()=>{data(){return{test:"混入测试",}},methods:{divClick(){console.log("divClickMixins");......
  • Java文件操作 获取文件扩展名
    publicclassFilenameUtil{/**Java文件操作获取文件扩展名**Createdon:2011-8-2*Author:blueeagle*/publicstaticStringgetExtensionName(Stringfilename){if((filename!=null)&&(filename.length()>0)){intdot=f......
  • Java (Docker MySql)
    前沿加油每天进步一点就是无敌可以去官网下载Docker yuminstall-ydocker重启刷新停止sudosystemctlstartdockersudosystemctlstopdockersudosystemctlrestartdocker哈可以装客户端端dcocker直接安装就完事了  然后安装mysql然后遇到这样的......
  • Java定义常量的几种方法
    方法一采用接口(Interface)的中变量默认为staticfinal的特性。方法二采用了Java5.0中引入的Enum类型。方法三采用了在普通类中使用staticfinal修饰变量的方法。方法四类似方法三,但是通过函数来获取常量。/***MethodOne*/interfaceConstantInterface{StringSUNDAY=......
  • Vue指令_v-if&v-show
    VUE指令—v-if及v-showv-if条件性的渲染某元素,判定为true时渲染,否则不渲染,结合v-if-else和v-else使用<body><divid="app">年龄<inputtype="text"v-model="age">经判定,为:<spanv-if="age<=35">年轻人(35及以下)......
  • Vue指令_v-bind&v-model
    VUE指令—v-bind及v-modelv-bind:为HTML标签绑定属性值,如设置href,css样式等。当vue对象中的数据模型发生变化时,标签的属性值会随之发生变化。v-model:在表单元素上创建双向数据绑定。vue对象的data属性中的数据变化,视图展示会一起变化;视图数据发生变化,vue对象的data属性......
  • JavaScript-变量
    JavaScript-1.变量1.js引入方式a.内部脚本:将Js代码定义在script标签中 <script>window.alert("HELLOJS")//将我们指定的入参文案以弹框的形式显示出来document.write("hellojs!")//将入参文案写入到当前的HTML内容中console.log("helloj......
  • JavaScript-数据转换
    JavaScript-数据类型转换和运算符数据类型js中的数据类型分为:原始类型和引用类型,具体有如下类型:数据类型描述number数字(整数、小数、NaN(NotaNumber))string字符串,单双引皆可boolean布尔。true,falsenull对象为空undefined当声明的变量未初始化时......
  • JavaScript-JSON
    JavaScript-JSON1.自定义对象var对象名={属性名1:属性值1,属性名2:属性值2,属性名3:属性值3,函数名称:function(形参列表){}};语法调用属性和函数:对象名.属性名;对象名.函数名();2.json对象JSON对象:JavaScriptObjectNotation,JavaScript对......