springboot大文件上传

1.接口文件编写

@CrossOrigin(origins = "*")
@RestController
public class DemoController {

    @PostMapping("file/upload")
    public void upload(
            Long size, Long totalSize,
            Integer chunk, Integer totalChunks,
            String fileName, MultipartFile file) throws IOException {
        String path = System.getProperty("user.dir") + "\\service-01\\src\\main\\resources\\upload\\";

        String filePath = path + fileName;
        FileUtils.writeChunk(chunk, totalChunks, size, totalSize, filePath, file.getInputStream());
    }
}

2.大文件上传工具类实现

public class FileUtils {
    private static final Map<String, ChunkRemark> filesBuffer = new HashMap<>();

    @Data
    private static class ChunkRemark {
        private int n;
        private boolean[] mark;

        public ChunkRemark(int n) {
            this.n = n;
            mark = new boolean[n];
        }

        public void mark(int chunk) {
            mark[chunk] = true;
        }

        public boolean isLoaded() {
            for (int i = 0; i < n; i++) {
                if (!mark[i]) {
                    return false;
                }
            }
            return true;
        }
    }

    public static boolean isExists(String md5) {
        return filesBuffer.get(md5) != null;
    }


    public static void writeChunk(int chunk, int totalChunk, long size, long totalSize, String md5, InputStream is) {
        if (!isExists(md5)) {
            filesBuffer.put(md5, new ChunkRemark(totalChunk));
        }

        try (RandomAccessFile fp = new RandomAccessFile(md5, "rw");) {
            fp.setLength(totalSize);
            fp.seek((chunk - 1) * size);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = is.read(buf)) != -1) {
                fp.write(buf, 0, len);
                buf = new byte[1024];
            }
            synchronized (FileUtils.class) {
                filesBuffer.get(md5).mark(chunk - 1);

                if (filesBuffer.get(md5).isLoaded()) {
                    System.out.println("file collected!");
                    filesBuffer.remove(md5);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3.前端页面编写

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>

    <form action="http://localhost:9002/file/upload" method="post" enctype="multipart/form-data">
        <input type="file" id="file" name="file"/>
    </form>

    <script>
        $(function () {
            function fileSlice(file, piece = 1024) {
                let total = file.size;
                let start = 0;
                let end = start + piece;
                let chunks = [];
                while (start < total) {
                    chunks.push(file.slice(start, end));
                    start = end;
                    end = start + piece;
                }
                return chunks;
            }

            $("#file").on("change", function (e) {
               let file = e.target.files[0];
               let fileSize = file.size;
               let chunks = fileSlice(file);
                console.log(chunks.length)

               chunks.forEach((chunk, index) => {
                   let formData = new FormData();
                   formData.append("file", chunk);
                   formData.append("totalSize", fileSize);
                   formData.append("size", 1024);
                   formData.append("chunk", index + 1);
                   formData.append("totalChunks", chunks.length);
                   formData.append("fileName", file.name);

                   $.ajax({
                       url: "http://localhost:9002/file/upload",
                       type: "post",
                       contentType: false,
                       processData: false,
                       data: formData,
                   })

               });

            });
        });
    </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 16宿命:用概率思维提高你的胜算 以前的我是风险厌恶者,不喜欢去冒险,但是人生放弃了冒险,也就放弃了无数的可能。 ...
    yichen大刀阅读 6,099评论 0 4
  • 公元:2019年11月28日19时42分农历:二零一九年 十一月 初三日 戌时干支:己亥乙亥己巳甲戌当月节气:立冬...
    石放阅读 6,913评论 0 2
  • 昨天考过了阿里规范,心里舒坦了好多,敲代码也犹如神助。早早完成工作回家喽
    常亚星阅读 3,051评论 0 1
  • 三军可夺气,将军可夺心。是故朝气锐,昼气惰,暮气归。善用兵者,避其锐气,击其惰归,此治气者也。以治待乱,以静待哗,...
    生姜牛奶泡腾片阅读 1,605评论 0 1
  • 追星逐渐从心理上的偏好转向致力于打榜花钱的形式主义,明星信息的公开化与非法售卖也导致私生饭等盲目甚至变性的行...
    黑彧阅读 1,626评论 0 3