当前位置:   article > 正文

SpringBoot+前端文件分片上传_springboot 获取处理前端传的文件切片

springboot 获取处理前端传的文件切片

在日常生活中,文件上传相关的操作随处可见,大到处理大数据量的文件,小到头像上传,都离不开文件上传操作,但是当一个文件的大小超过了某个阈值时,这个文件的上传过程就会变得及其的慢,且会消耗大量网络资源,这是我们不愿意看到的,所以,文件分片上传孕育而生。

什么是文件分片上传?

文件分片上传就是将一整个文件分为几个小块,然后将这几个小块分别传送给服务器,从而实现分片上传。

上图为文件分片的图解,在本图中,我们假定每一个分片都为67MB。(只是演示,实际文件分片需要考虑更多细节)

如果当我们分片到最后一片的时候,我们就会直接将剩余所有空间存放到一个切片中,不管大小是否足够我们指定的大小。

注意:这里的最后一片是指剩余的文件大小小于等于我们分片指定大小的情况。

文件分片时需要考虑什么?

在进行文件分片时,我们需要按照实际情况下文件大小来指定每一个切片的大小。并且需要在切片后将所有切片数量做记录,具体流程将以列表形式呈现:

前端

  1. 获取文件,并规定一些常量(如切片大小,和后端约定的状态信息等等)
  2. 开始文件切片,并将切片存储到数组中
  3. 切片数组中的切片转换为二进制形式(原数组不变,只取数据)并添加到缓冲区(SparkMD5库提供的缓冲区)中
  4. 确保所有切片全都存入缓冲区(这时候缓冲区内的其实就是我们的整体文件,所有切片都合并了),然后计算文件hash.
  5. 开始对后端进行数据交互(上传分片,提示合并,检查是否已经上传文件 等)

后端

  1. 从前端获取相关信息(如文件hash,文件名,切片文件等)
  2. 检查是否已经上传过相同文件
  3. 等待所有切片文件存储完成,并接收前端的合并通知(这一条看个人,也可以在后端直接计算是否拿到所有切片)
  4. 确保拿到所有切片文件后,开始读取切片文件的二进制信息,并将其添加到缓冲区中
  5. 读取完全部文件后,将缓冲区数据写入指定文件中
  6. 将切片文件全部删除

以上是文件分片上传时前后端的基础流程(可能有些地方写的不够严谨,希望各位大佬指教)

特别注意:在文件合并时要注意分片文件合并的顺序问题,如果顺序颠倒,那文件自然无法正常显示。

个人建议所有分片文件命名后面跟上一个索引.

代码实战

声明:此代码没有考虑过多细节,只是作为一个基础展示的案例。

前端

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport"
  6. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>Document</title>
  9. <style>
  10. .msg{
  11. font-size: 20px;
  12. font-weight: bold;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <input type="file">
  18. <p class="msg"></p>
  19. <script src="js/axios.js"></script>
  20. <script src="js/spark-md5.js"></script>
  21. <script>
  22. const statusCode = {
  23. UPLOAD_SUCCESS: 200,
  24. NOT_UPLOAD: 202,
  25. ALREADY_UPLOAD: 1000,
  26. UPLOAD_FAILED: 1004
  27. }
  28. let chunkSize = 2 * 1024 * 1024
  29. let msg = document.querySelector(".msg")
  30. let file = document.querySelector("input[type='file']")
  31. file.addEventListener("change", async (e) => {
  32. let fileList = e.target.files
  33. let file = fileList[0]
  34. let chunkArr = chunk(file, chunkSize)
  35. let fileHash = await hash(chunkArr)
  36. let filename = file.name
  37. //false:没上传 true:上传过了
  38. let hasUpload = await check(fileHash, filename)
  39. if (!hasUpload) {
  40. let promises = []
  41. for (let i = 0; i < chunkArr.length; i++) {
  42. //将最后的返回结果添加到数组中
  43. let res = await upload(fileHash, chunkArr, i, filename)
  44. promises.push(res)
  45. }
  46. Promise.all(promises).then(res => {
  47. mergeNotify(fileHash, filename, chunkArr.length)
  48. msg.innerHTML="文件上传成功"
  49. msg.style.color="green"
  50. }).catch(err => {
  51. console.error(err)
  52. })
  53. } else {
  54. //文件上传过了,无需再次上传
  55. msg.innerHTML="文件已经上传!!"
  56. msg.style.color="red"
  57. }
  58. })
  59. /**
  60. *
  61. * @param file 文件File对象
  62. * @param chunkSize 每一个切片的大小
  63. * @return {[]} 返回切片数组
  64. */
  65. const chunk = (file, chunkSize) => {
  66. let res = []
  67. for (let i = 0; i < file.size; i += chunkSize) {
  68. res.push(file.slice(i, i + chunkSize))
  69. }
  70. return res
  71. }
  72. /**
  73. *
  74. * @param chunks 切片数组
  75. * @return string 返回文件hash
  76. */
  77. const hash = async (chunks) => {
  78. let sparkMD5 = new SparkMD5.ArrayBuffer()
  79. //存储每个切片加密的任务状态,全部完成后,才会返回最终hash
  80. let promises = []
  81. //将切片数组所有切片转为二进制,并将其合并为一个完整文件
  82. for (let i = 0; i < chunks.length; i++) {
  83. //由于hash加密耗时,所以我们采用异步
  84. let promise = new Promise((resolve, reject) => {
  85. let fileReader = new FileReader()//使用fileReader对象将文件切片转为二进制
  86. fileReader.readAsArrayBuffer(chunks[i])
  87. fileReader.onload = (e) => {
  88. //添加到SparkMD5中,等所有切片添加完毕后,获取最终哈希
  89. sparkMD5.append(e.target.result)
  90. //每次添加成功后返回一个成功状态
  91. resolve()
  92. }
  93. fileReader.onerror = (e) => {
  94. reject(e.target.error)
  95. }
  96. })
  97. //将该promise任务添加到promise数组中
  98. promises.push(promise)
  99. }
  100. //当所有加密任务全都完成后,返回加密后的完整文件hash
  101. return await Promise.all(promises).then(res => {
  102. return sparkMD5.end()
  103. }).catch(err => {
  104. console.error("Hash加密出现问题")
  105. })
  106. }
  107. /***
  108. *
  109. * @param hash 文件hash
  110. * @param chunks 切片数组
  111. * @param currentIndex 当前切片索引
  112. * @param filename 文件名
  113. * @return 返回Promise,用于检测当前切片是否上传成功
  114. */
  115. const upload = (hash, chunks, currentIndex, filename) => {
  116. return new Promise((resolve, reject) => {
  117. let formData = new FormData()
  118. formData.append("hash", hash)
  119. formData.append("chunkIndex", currentIndex)
  120. formData.append("filename", filename)
  121. formData.append("chunkBody", chunks[currentIndex])
  122. axios.post("http://localhost:8080/upload", formData).then(res => {
  123. //出现无法判断是否成功的问题,推荐判断是否成功在Promise.all中判断
  124. resolve("")
  125. }).catch(err => {
  126. reject(err)
  127. })
  128. })
  129. }
  130. /***
  131. * 通知后端接口:可以开始合并任务了
  132. * @param hash 文件hash
  133. * @param filename 文件名
  134. */
  135. const mergeNotify = (hash, filename, chunksLen) => {
  136. let formData = new FormData()
  137. formData.append("filename", filename)
  138. formData.append("fileHash", hash)
  139. formData.append("totalChunk", chunksLen)
  140. axios.post("http://localhost:8080/merge", formData).then(res => {})
  141. }
  142. /**
  143. * 检查文件是否上传
  144. * @param hash 文件hash
  145. * @param filename 文件名
  146. * @return {Promise<Boolean>} 返回一个Promise对象
  147. */
  148. const check = async (hash, filename) => {
  149. let formData = new FormData()
  150. formData.append("filename", filename)
  151. formData.append("fileHash", hash)
  152. let hasUpload = axios.post("http://localhost:8080/check", formData).then(res => {
  153. let result;
  154. //判断是否上传过该文件
  155. if (res.data.code === statusCode.NOT_UPLOAD) {
  156. result = false
  157. } else {
  158. result = true
  159. }
  160. //返回promise对象
  161. return Promise.resolve(result)
  162. })
  163. return hasUpload
  164. }
  165. </script>
  166. </body>
  167. </html>

后端

entity

BaseFile
  1. package com.cc.fileupload.entity;
  2. /**
  3. * @author CC
  4. * @date Created in 2024/2/7 12:15
  5. */
  6. public class BaseFile {
  7. /**
  8. * 文件hash
  9. */
  10. private String fileHash;
  11. public BaseFile() {
  12. }
  13. public BaseFile(String fileHash, String filename) {
  14. this.fileHash = fileHash;
  15. this.filename = filename;
  16. }
  17. /**
  18. * 文件名
  19. */
  20. private String filename;
  21. @Override
  22. public String toString() {
  23. return "BaseFile{" +
  24. "fileHash='" + fileHash + '\'' +
  25. ", filename='" + filename + '\'' +
  26. '}';
  27. }
  28. public String getFileHash() {
  29. return fileHash;
  30. }
  31. public void setFileHash(String fileHash) {
  32. this.fileHash = fileHash;
  33. }
  34. public String getFilename() {
  35. return filename;
  36. }
  37. public void setFilename(String filename) {
  38. this.filename = filename;
  39. }
  40. }
MergeFile
  1. package com.cc.fileupload.entity;
  2. /**
  3. * @author CC
  4. * @date Created in 2024/2/7 11:27
  5. */
  6. public class MergeFile {
  7. /**
  8. * 文件名
  9. */
  10. private String filename;
  11. /**
  12. * 文件hash
  13. */
  14. private String fileHash;
  15. /**
  16. * 切片总数
  17. */
  18. private Integer totalChunk;
  19. public String getFilename() {
  20. return filename;
  21. }
  22. public void setFilename(String filename) {
  23. this.filename = filename;
  24. }
  25. public String getFileHash() {
  26. return fileHash;
  27. }
  28. public void setFileHash(String fileHash) {
  29. this.fileHash = fileHash;
  30. }
  31. public Integer getTotalChunk() {
  32. return totalChunk;
  33. }
  34. @Override
  35. public String toString() {
  36. return "MergeFile{" +
  37. "filename='" + filename + '\'' +
  38. ", fileHash='" + fileHash + '\'' +
  39. ", totalChunk=" + totalChunk +
  40. '}';
  41. }
  42. public void setTotalChunk(Integer totalChunk) {
  43. this.totalChunk = totalChunk;
  44. }
  45. public MergeFile() {
  46. }
  47. public MergeFile(String filename, String fileHash, Integer totalChunk) {
  48. this.filename = filename;
  49. this.fileHash = fileHash;
  50. this.totalChunk = totalChunk;
  51. }
  52. }
UploadFile
  1. package com.cc.fileupload.entity;
  2. import org.springframework.web.bind.annotation.RequestParam;
  3. import org.springframework.web.multipart.MultipartFile;
  4. /**
  5. * @author CC
  6. * @date Created in 2024/2/7 10:33
  7. */
  8. public class UploadFile {
  9. /**
  10. * 传入的切片文件
  11. */
  12. private MultipartFile chunkBody;
  13. /**
  14. * 文件hash
  15. */
  16. private String hash;
  17. /**
  18. * 文件名
  19. */
  20. private String filename;
  21. /**
  22. * 当前切片的索引号
  23. */
  24. private Integer chunkIndex;
  25. public MultipartFile getChunkBody() {
  26. return chunkBody;
  27. }
  28. public void setChunkBody(MultipartFile chunkBody) {
  29. this.chunkBody = chunkBody;
  30. }
  31. public String getHash() {
  32. return hash;
  33. }
  34. public void setHash(String hash) {
  35. this.hash = hash;
  36. }
  37. public String getFilename() {
  38. return filename;
  39. }
  40. public void setFilename(String filename) {
  41. this.filename = filename;
  42. }
  43. public Integer getChunkIndex() {
  44. return chunkIndex;
  45. }
  46. public void setChunkIndex(Integer chunkIndex) {
  47. this.chunkIndex = chunkIndex;
  48. }
  49. @Override
  50. public String toString() {
  51. return "UploadFile{" +
  52. "chunkBody=" + chunkBody +
  53. ", hash='" + hash + '\'' +
  54. ", filename='" + filename + '\'' +
  55. ", chunkIndex=" + chunkIndex +
  56. '}';
  57. }
  58. }

util

Helper
  1. package com.cc.fileupload.util;
  2. /**
  3. * @author CC
  4. * @date Created in 2024/2/7 10:49
  5. */
  6. public class Helper {
  7. /**
  8. * 构建切片文件名
  9. *
  10. * @param baseName 基础文件名
  11. * @param index 文件索引
  12. * @return 返回切片文件名
  13. */
  14. public static String buildChunkName(String baseName, Integer index) {
  15. int i = baseName.lastIndexOf(".");
  16. String prefix = baseName.substring(0, i).replaceAll("\\.", "_");
  17. return prefix + "_part_" + index;
  18. }
  19. public static <T> ResultFormat<T> getReturnMsg(Integer code, T data, String msg) {
  20. return new ResultFormat<T>(data, msg, code);
  21. }
  22. public static <T> ResultFormat<T> getReturnMsg(Integer code, T data) {
  23. return new ResultFormat<T>(data, code);
  24. }
  25. public static ResultFormat<String> getReturnMsg(Integer code, String msg) {
  26. return new ResultFormat<>(msg, code);
  27. }
  28. public static ResultFormat<Integer> getReturnMsg(Integer code){
  29. return new ResultFormat<>(code);
  30. }
  31. //
  32. // public static void main(String[] args) {
  33. // String s = buildChunkName("test.xx.txt", 1);
  34. // System.out.println(s);
  35. // }
  36. }
ResultFormat
  1. package com.cc.fileupload.util;
  2. /**
  3. * @author CC
  4. * @date Created in 2024/2/7 11:46
  5. */
  6. public class ResultFormat<T> {
  7. private T data;
  8. private String msg;
  9. private Integer code;
  10. @Override
  11. public String toString() {
  12. return "{" +
  13. "data=" + data +
  14. ", msg='" + msg + '\'' +
  15. ", code=" + code +
  16. '}';
  17. }
  18. public T getData() {
  19. return data;
  20. }
  21. public void setData(T data) {
  22. this.data = data;
  23. }
  24. public String getMsg() {
  25. return msg;
  26. }
  27. public void setMsg(String msg) {
  28. this.msg = msg;
  29. }
  30. public Integer getCode() {
  31. return code;
  32. }
  33. public void setCode(Integer code) {
  34. this.code = code;
  35. }
  36. public ResultFormat(String msg, Integer code) {
  37. this.msg = msg;
  38. this.code = code;
  39. }
  40. public ResultFormat(Integer code) {
  41. this.code = code;
  42. }
  43. public ResultFormat(T data, Integer code) {
  44. this.data = data;
  45. this.code = code;
  46. }
  47. public ResultFormat(T data, String msg, Integer code) {
  48. this.data = data;
  49. this.msg = msg;
  50. this.code = code;
  51. }
  52. }
StatusCode 
  1. package com.cc.fileupload.util;
  2. /**
  3. * @author CC
  4. * @date Created in 2024/2/7 11:46
  5. */
  6. public enum StatusCode {
  7. UPLOAD_SUCCESS(200),
  8. NOT_UPLOAD(202),
  9. ALREADY_UPLOAD(1000),
  10. UPLOAD_FAILED(1004);
  11. private java.lang.Integer code;
  12. StatusCode(java.lang.Integer code) {
  13. this.code = code;
  14. }
  15. public java.lang.Integer getCode() {
  16. return code;
  17. }
  18. public void setCode(java.lang.Integer code) {
  19. this.code = code;
  20. }
  21. }

service

UploadService
  1. package com.cc.fileupload.service;
  2. import com.cc.fileupload.entity.BaseFile;
  3. import com.cc.fileupload.entity.MergeFile;
  4. import com.cc.fileupload.entity.UploadFile;
  5. import com.cc.fileupload.util.ResultFormat;
  6. import java.io.File;
  7. /**
  8. * @author CC
  9. * @date Created in 2024/2/7 10:46
  10. */
  11. public interface UploadService {
  12. /**
  13. * 上传文件并保存切片的操作
  14. *
  15. * @param uploadFile 文件上传实体类
  16. * @return 返回状态信息
  17. */
  18. ResultFormat upload(UploadFile uploadFile);
  19. /**
  20. * 合并文件切片
  21. *
  22. * @param mergeFile 合并文件实体类
  23. */
  24. void merge(MergeFile mergeFile);
  25. /**
  26. * 对文件的切片做删除操作
  27. * @param mergeFile 合并文件实体类
  28. */
  29. void deleteChunks(MergeFile mergeFile);
  30. /**
  31. *
  32. * @param baseFile 检查文件是否已经上传
  33. * @return 返回状态信息
  34. */
  35. ResultFormat<Integer> checkHasUpload(BaseFile baseFile);
  36. }
IUploadService
  1. package com.cc.fileupload.service.impl;
  2. import com.cc.fileupload.entity.BaseFile;
  3. import com.cc.fileupload.entity.MergeFile;
  4. import com.cc.fileupload.entity.UploadFile;
  5. import com.cc.fileupload.service.UploadService;
  6. import com.cc.fileupload.util.Helper;
  7. import com.cc.fileupload.util.ResultFormat;
  8. import com.cc.fileupload.util.StatusCode;
  9. import org.springframework.stereotype.Service;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import java.io.File;
  12. import java.io.FileOutputStream;
  13. import java.io.IOException;
  14. import java.io.OutputStream;
  15. import java.nio.file.Files;
  16. /**
  17. * @author CC
  18. * @date Created in 2024/2/7 10:46
  19. */
  20. @Service
  21. public class IUploadService implements UploadService {
  22. private static final String BASE_PATH = "D:\\桌面\\图片";
  23. @Override
  24. public ResultFormat<java.lang.Integer> checkHasUpload(BaseFile mergeFile) {
  25. String fileHash = mergeFile.getFileHash();
  26. String filename = mergeFile.getFilename();
  27. File folder = new File(BASE_PATH, fileHash);
  28. if (folder.exists()) {
  29. File file = new File(folder, filename);
  30. if (file.exists()) {
  31. return Helper.getReturnMsg(StatusCode.ALREADY_UPLOAD.getCode());
  32. }
  33. }
  34. return Helper.getReturnMsg(StatusCode.NOT_UPLOAD.getCode());
  35. }
  36. @Override
  37. public ResultFormat upload(UploadFile uploadFile) {
  38. String filename = uploadFile.getFilename();
  39. String hash = uploadFile.getHash();
  40. java.lang.Integer currentChunkIndex = uploadFile.getChunkIndex();
  41. MultipartFile chunkBody = uploadFile.getChunkBody();
  42. //根据hash来创建文件夹,有助于检测是否上传
  43. File folder = new File(BASE_PATH, hash);
  44. if (!folder.exists()) {
  45. folder.mkdirs();
  46. }
  47. //这里获取需要写入的文件路径和文件名
  48. File file1 = new File(folder, Helper.buildChunkName(filename, currentChunkIndex));
  49. try {
  50. //文件写入
  51. chunkBody.transferTo(file1);
  52. return Helper.getReturnMsg(StatusCode.UPLOAD_SUCCESS.getCode(), "上传成功");
  53. } catch (IOException e) {
  54. System.out.println("出现错误");
  55. e.printStackTrace();
  56. }
  57. //对文件进行写入
  58. return Helper.getReturnMsg(StatusCode.UPLOAD_FAILED.getCode(), "上传失败");
  59. }
  60. @Override
  61. public void deleteChunks(MergeFile mergeFile) {
  62. File hashFolder = new File(BASE_PATH, mergeFile.getFileHash());
  63. java.lang.Integer totalChunk = mergeFile.getTotalChunk();
  64. String filename = mergeFile.getFilename();
  65. for (int i = 0; i < totalChunk; i++) {
  66. //获取切片
  67. File tmpChunkFile = new File(hashFolder, Helper.buildChunkName(filename, i));
  68. tmpChunkFile.delete();
  69. }
  70. }
  71. @Override
  72. public void merge(MergeFile mergeFile) {
  73. String hash = mergeFile.getFileHash();
  74. String filename = mergeFile.getFilename();
  75. java.lang.Integer totalChunk = mergeFile.getTotalChunk();
  76. //文件hash的Folder
  77. File hashFolder = new File(BASE_PATH, hash);
  78. OutputStream os = null;
  79. //检查是否有该hash目录
  80. try {
  81. if (hashFolder.exists()) {
  82. //指定最后输出的文件名
  83. os = new FileOutputStream(new File(hashFolder, filename));
  84. for (int i = 0; i < totalChunk; i++) {
  85. //获取切片
  86. File tmpChunkFile = new File(hashFolder, Helper.buildChunkName(filename, i));
  87. //数据读取并写入缓存区
  88. byte[] bytes = Files.readAllBytes(tmpChunkFile.toPath());
  89. //将每一个切片数据读取写入缓存区
  90. os.write(bytes);
  91. }
  92. //在将每一个切片的字节全都写入缓冲区后,最后合并输出文件
  93. os.flush();
  94. //输出后清理临时文件
  95. deleteChunks(mergeFile);
  96. }
  97. } catch (IOException e) {
  98. e.printStackTrace();
  99. } finally {
  100. //资源关闭
  101. if (os != null) {
  102. try {
  103. os.close();
  104. } catch (IOException e) {
  105. e.printStackTrace();
  106. }
  107. }
  108. }
  109. }
  110. }

controller

UploadController
  1. package com.cc.fileupload.controller;
  2. import com.cc.fileupload.entity.BaseFile;
  3. import com.cc.fileupload.entity.MergeFile;
  4. import com.cc.fileupload.entity.UploadFile;
  5. import com.cc.fileupload.service.UploadService;
  6. import com.cc.fileupload.util.ResultFormat;
  7. import org.springframework.web.bind.annotation.*;
  8. import javax.annotation.Resource;
  9. /**
  10. * @author CC
  11. * @date Created in 2024/2/7 9:46
  12. */
  13. @RestController
  14. @CrossOrigin
  15. public class UploadController {
  16. @Resource
  17. private UploadService uploadService;
  18. @RequestMapping("/upload")
  19. public ResultFormat upload(@ModelAttribute UploadFile uploadFile) {
  20. System.out.println("上传");
  21. return uploadService.upload(uploadFile);
  22. }
  23. @RequestMapping("/merge")
  24. public void merge(@ModelAttribute MergeFile mergeFile) {
  25. uploadService.merge(mergeFile);
  26. }
  27. @RequestMapping("/check")
  28. public ResultFormat check(@ModelAttribute BaseFile file) {
  29. System.out.println("检查");
  30. return uploadService.checkHasUpload(file);
  31. }
  32. }

github链接

前端:GitHub - wewCc/fileUpload_frontend: 文件上传前端文件上传前端. Contribute to wewCc/fileUpload_frontend development by creating an account on GitHub.icon-default.png?t=N7T8https://github.com/wewCc/fileUpload_frontend

后端:https://github.com/wewCc/fileUploadicon-default.png?t=N7T8https://github.com/wewCc/fileUpload

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/528060
推荐阅读
相关标签
  

闽ICP备14008679号