JAVA大文件分片上传

JAVA大文件分片上传

一 、思路

    1. 将大文件拆分成多个小文件多次上传, 全部上传完成后, 将这些分片合并成原始文件
    1. 合并过程中需要按顺序合并, 所以需要 chunkIndex 定位顺序
    1. 需要知道什么时候合并, 所以需要 totalChunks 确定分片总数, 后端判断 上传数量(后端记录) == 分片总数
    1. fileHash作为唯一key来标识文件, 比如: MD5计算
    1. 合并完成后删除分片, 清空缓存
    1. 防止文件占用过多jvm内存, 应使用流的方式进行文件传输, 避免使用file.getBytes()类似的方法导致oom, 本示例使用FileChannel的方式进行文件传输

二、代码示例

java 复制代码
package org.example.controller;


import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/api/test")
public class TestController {

    private Map<String, AtomicInteger> CHUNK_TOTAL_MAP = new ConcurrentHashMap<>();

    /**
     * 大文件分片上传
     * 思路: 1. 将大文件拆分成多个小文件多次上传, 全部上传完成后, 将这些分片合并成原始文件
     *      2. 合并过程中需要按顺序合并, 所以需要 chunkIndex 定位顺序
     *      3. 需要知道什么时候合并, 所以需要 totalChunks 确定分片总数, 后端判断 上传数量(后端记录) == 分片总数
     *      4. fileHash作为唯一key来标识文件
     *      5. 合并完成后删除分片, 清空缓存
     * @param multipartFile 文件片段
     * @param chunkIndex 分片顺序编号, 从0开始
     * @param totalChunks 分片总数
     * @param fileHash 原文件hash值, 作为唯一key
     * @param fileName 合并后的文件名
     * @param endWith 合并后的文件后缀
     * @return
     */
    @PostMapping("/upload")
    public ResponseEntity<Object> upload(@RequestPart MultipartFile multipartFile,
                                         @RequestParam int chunkIndex,
                                         @RequestParam int totalChunks,
                                         @RequestParam String fileHash,
                                         @RequestParam String fileName,
                                         @RequestParam String endWith){

        //临时存储分片路径
        String chunkDir = "D:/file/upload/"+fileHash;
        String chunkPath = "/chunk_" + chunkIndex;

        //创建目录
        try {
            Files.createDirectories(Path.of(chunkDir));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //保存分片
        writeToChunk(multipartFile, chunkPath);

        //更新上传分片数量
        CHUNK_TOTAL_MAP.putIfAbsent(fileHash, new AtomicInteger(0));
        int uploadChunks = CHUNK_TOTAL_MAP.get(fileHash).incrementAndGet();

        //判断是否开始合并
        if(uploadChunks == totalChunks){
            mergeChunk(chunkDir, fileName, totalChunks, endWith);
            CHUNK_TOTAL_MAP.remove(fileHash); //清空缓存
        }

        return ResponseEntity.ok(CHUNK_TOTAL_MAP);
    }

    /**
     * 合并分片
     * @param chunkDir 文件保存路径
     * @param fileName 文件名
     * @param totalChunks 分片总数
     * @param endWith 合并后的文件后缀
     */
    private void mergeChunk(String chunkDir, String fileName, int totalChunks, String endWith) {
        String filePath = chunkDir + "/" +fileName + "." + endWith;
        try (FileChannel outChannel = (FileChannel) Files.newByteChannel(Path.of(filePath), StandardOpenOption.CREATE, StandardOpenOption.APPEND)){

            for (int i = 0; i < totalChunks; i++) {
                //读取分片
                String chunkPath = "/chunk_" + i;
                try(FileChannel inChannel = (FileChannel) Files.newByteChannel(Path.of(chunkPath), StandardOpenOption.READ)){
                    //合并分片到主文件
                    outChannel.transferFrom(inChannel,outChannel.size(), inChannel.size());
                    //删除分片
                    Files.deleteIfExists(Path.of(chunkPath));
                }catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 保存分片
     * @param multipartFile
     * @param chunkPath
     */
    private void writeToChunk(MultipartFile multipartFile, String chunkPath) {

        try (FileChannel outChannel = (FileChannel) Files.newByteChannel(Path.of(chunkPath), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
             InputStream inputStream = multipartFile.getInputStream();
             ReadableByteChannel inChannel =  Channels.newChannel(inputStream);){

            long chunkSize = multipartFile.getSize();
            outChannel.transferFrom(inChannel,0, chunkSize);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
相关推荐
500841 小时前
昇腾 CANN 的五层架构,到底分了哪五层
java·人工智能·分布式·架构·ocr·wpf
摇滚侠2 小时前
Java 零基础全套教程,File 类与 IO 流,笔记 177-178
java·开发语言·笔记
雨落在了我的手上2 小时前
初始java(十):类和对象(⼆)
java·开发语言
莫雪歌3 小时前
Java AI 应用开发实践:基于 Spring Boot 实现 Chat、Memory、RAG 与 Tool Calling
java·aigc
SmartBrain4 小时前
AI全栈开发(SDD):慢病管理系统工程级设计
java·大数据·开发语言·人工智能·架构·aigc
梦想CAD控件4 小时前
网页端对DWG图纸进行预览与批注(CAD轻量化)
java·前端·javascript
老毛肚4 小时前
Spring boot 特性和自写Reids组件
java·spring boot·后端
极光代码工作室4 小时前
基于SpringBoot的课程管理系统
java·springboot·web开发·后端开发
JustNow_Man4 小时前
【opencode】安装使用daytona沙箱插件
android·java·javascript
武子康5 小时前
Java-05 深入浅出 MyBatis动态SQL与参数拼接完全指南
java·spring boot·后端