{"id":14983061,"url":"https://github.com/gaoyuyue/myuploader-backend","last_synced_at":"2025-04-05T08:07:42.298Z","repository":{"id":37421516,"uuid":"157482887","full_name":"gaoyuyue/MyUploader-Backend","owner":"gaoyuyue","description":"单文件上传，多文件上传，大文件上传，断点续传，文件秒传，图片上传","archived":false,"fork":false,"pushed_at":"2021-06-05T13:57:20.000Z","size":28,"stargazers_count":491,"open_issues_count":5,"forks_count":218,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-04-05T08:07:37.180Z","etag":null,"topics":["java","maven","mybatis","spring","spring-boot","springmvc"],"latest_commit_sha":null,"homepage":"https://gaoyuyue.github.io/MyUploader","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gaoyuyue.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-11-14T03:09:06.000Z","updated_at":"2025-03-20T05:59:19.000Z","dependencies_parsed_at":"2022-07-21T09:02:32.446Z","dependency_job_id":null,"html_url":"https://github.com/gaoyuyue/MyUploader-Backend","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gaoyuyue%2FMyUploader-Backend","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gaoyuyue%2FMyUploader-Backend/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gaoyuyue%2FMyUploader-Backend/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gaoyuyue%2FMyUploader-Backend/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gaoyuyue","download_url":"https://codeload.github.com/gaoyuyue/MyUploader-Backend/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247305934,"owners_count":20917208,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["java","maven","mybatis","spring","spring-boot","springmvc"],"created_at":"2024-09-24T14:06:40.272Z","updated_at":"2025-04-05T08:07:42.273Z","avatar_url":"https://github.com/gaoyuyue.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MyUploader-Backend\n\u003e 单文件上传，多文件上传，大文件上传，断点续传，文件秒传，图片上传\n\u003e \n\u003e 前端项目地址： [https://github.com/gaoyuyue/MyUploader](https://github.com/gaoyuyue/MyUploader)\n\n# 简介\n采用前后端分离的方式进行开发，实现了几种常用的文件上传功能。 前端采用 vue.js + plupload + element-ui 实现了文件在浏览器端的发送, 后端采用 spring boot + spring + spring mvc + mybatis 实现了文件在服务器端的接收和存储。\n\n***本项目为后端实现***\n\n# 效果图\n\u003e 演示地址： [https://gaoyuyue.github.io/MyUploader](https://gaoyuyue.github.io/MyUploader)\n\u003e\n\u003e *ps: 用git pages搭建的静态页面，只能演示前端功能*\n### 单文件上传\n![](https://i.imgur.com/vBr8ZJq.gif)\n### 多文件上传\n![](https://i.imgur.com/Db6eaMJ.gif)\n### 大文件上传\n![](https://i.imgur.com/qAyksE8.gif)\n### 断点续传\n![](https://i.imgur.com/I1G01MT.gif)\n### 文件秒传\n![](https://i.imgur.com/XHZHGeo.gif)\n### 图片上传\n![](https://i.imgur.com/HFZQnV3.gif)\n\n# 后端实现\n## 未分块上传\n采用MultipartFile接收上传文件并使用FileOutputStream写入文件\n```java\n/**\n * 写入文件\n * @param target\n * @param src\n * @throws IOException\n */\npublic static void write(String target, InputStream src) throws IOException {\n    OutputStream os = new FileOutputStream(target);\n    byte[] buf = new byte[1024];\n    int len;\n    while (-1 != (len = src.read(buf))) {\n        os.write(buf,0,len);\n    }\n    os.flush();\n    os.close();\n}\n```\n## 分块上传\n采用MultipartFile接收上传文件的分块文件，上传参数包括：size：文件大小，chunk:分块号，chunks:总分块数\n```java\n@PostMapping(\"/\")\npublic void upload(String name,\n                   String md5,\n                   Long size,\n                   Integer chunks,\n                   Integer chunk,\n                   MultipartFile file) throws IOException {\n    if (chunks != null \u0026\u0026 chunks != 0) {\n        fileService.uploadWithBlock(name, md5,size,chunks,chunk,file);\n    } else {\n        fileService.upload(name, md5,file);\n    }\n}\n```\n### 分块上传信息的存储\n使用Map来存储分块的上传信息,key为文件唯一标识由前端发送这里采用文件MD5作为文件的唯一标识，value为自定义的静态内部类，其中name属性为文件在服务器端存储的随机文件名其在该文件的第一个分块上传到服务器时随机生成(UUID)，boolean数组记录了分块的上传情况已上传置为true。\n```java\n/**\n * 分块上传工具类\n */\npublic class UploadUtils {\n    /**\n     * 内部类记录分块上传文件信息\n     */\n    private static class Value {\n        String name;\n        boolean[] status;\n\n        Value(int n) {\n            this.name = generateFileName();\n            this.status = new boolean[n];\n        }\n    }\n\n    private static Map\u003cString, Value\u003e chunkMap = new HashMap\u003c\u003e();\n\n    /**\n     * 判断文件所有分块是否已上传\n     * @param key\n     * @return\n     */\n    public static boolean isUploaded(String key) {\n        if (isExist(key)) {\n            for (boolean b : chunkMap.get(key).status) {\n                if (!b) {\n                    return false;\n                }\n            }\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * 判断文件是否有分块已上传\n     * @param key\n     * @return\n     */\n    private static boolean isExist(String key) {\n        return chunkMap.containsKey(key);\n    }\n\n    /**\n     * 为文件添加上传分块记录\n     * @param key\n     * @param chunk\n     */\n    public static void addChunk(String key, int chunk) {\n        chunkMap.get(key).status[chunk] = true;\n    }\n\n    /**\n     * 从map中删除键为key的键值对\n     * @param key\n     */\n    public static void removeKey(String key) {\n        if (isExist(key)) {\n            chunkMap.remove(key);\n        }\n    }\n\n    /**\n     * 获取随机生成的文件名\n     * @param key\n     * @param chunks\n     * @return\n     */\n    public static String getFileName(String key, int chunks) {\n        if (!isExist(key)) {\n            synchronized (UploadUtils.class) {\n                if (!isExist(key)) {\n                    chunkMap.put(key, new Value(chunks));\n                }\n            }\n        }\n        return chunkMap.get(key).name;\n    }\n}\n```\n### 分块写入文件\n使用RandomAccessFile随机读写文件，通过targetSize指定文件的大小，通过seek定位分块在文件中对应位置，通过write方法进行写入。\n```java\n/**\n * 分块写入文件\n * @param target\n * @param targetSize\n * @param src\n * @param srcSize\n * @param chunks\n * @param chunk\n * @throws IOException\n */\npublic static void writeWithBlok(String target, Long targetSize, InputStream src, Long srcSize, Integer chunks, Integer chunk) throws IOException {\n    RandomAccessFile randomAccessFile = new RandomAccessFile(target,\"rw\");\n    randomAccessFile.setLength(targetSize);\n    if (chunk == chunks - 1) {\n        randomAccessFile.seek(targetSize - srcSize);\n    } else {\n        randomAccessFile.seek(chunk * srcSize);\n    }\n    byte[] buf = new byte[1024];\n    int len;\n    while (-1 != (len = src.read(buf))) {\n        randomAccessFile.write(buf,0,len);\n    }\n    randomAccessFile.close();\n}\n\n```\n### 分块上传逻辑\n每次分块上传时首先获取对应文件在服务器端生成的随机文件名，如果不存在即在这之前还没有分块上传，则创建文件分块存储信息的键值对并存入map中，同时返回刚生成的随机文件名。然后将分块写入文件，同时将boolean数组中当前对应分块的位置置为true。最后判断该文件的所有分块是否全部上传，如果已全部上传完成则将文件信息写入数据库同时删除map中对应的键值对。\n\u003e ps: 曾用文件夹存储上传分块，当分块全部上传完成时按顺序合并文件夹内所有分块，然后删除文件夹，后来发现RandomAccessFile果断弃坑。\n```java\n/**\n * 分块上传文件\n * @param md5\n * @param size\n * @param chunks\n * @param chunk\n * @param file\n * @throws IOException\n */\npublic void uploadWithBlock(String name,\n                            String md5,\n                            Long size,\n                            Integer chunks,\n                            Integer chunk,\n                            MultipartFile file) throws IOException {\n    String fileName = getFileName(md5, chunks);\n    FileUtils.writeWithBlok(UploadConfig.path + fileName, size, file.getInputStream(), file.getSize(), chunks, chunk);\n    addChunk(md5,chunk);\n    if (isUploaded(md5)) {\n        removeKey(md5);\n        fileDao.save(new File(name, md5,UploadConfig.path + fileName, new Date()));\n    }\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgaoyuyue%2Fmyuploader-backend","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgaoyuyue%2Fmyuploader-backend","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgaoyuyue%2Fmyuploader-backend/lists"}