You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.0 KiB

  1. package utils
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "strconv"
  6. )
  7. // 前端传来文件片与当前片为什么文件的第几片
  8. // 后端拿到以后比较次分片是否上传 或者是否为不完全片
  9. // 前端发送每片多大
  10. // 前端告知是否为最后一片且是否完成
  11. const breakpointDir = "./breakpointDir/"
  12. const finishDir = "./fileDir/"
  13. func BreakPointContinue(content []byte, fileName string, contentNumber int, contentTotal int, fileMd5 string) (error, string) {
  14. path := breakpointDir + fileMd5 + "/"
  15. err := os.MkdirAll(path, os.ModePerm)
  16. if err != nil {
  17. return err, path
  18. }
  19. err, pathc := makeFileContent(content, fileName, path, contentNumber)
  20. return err, pathc
  21. }
  22. func CheckMd5(content []byte, chunkMd5 string) (CanUpload bool) {
  23. fileMd5 := MD5V(content)
  24. if fileMd5 == chunkMd5 {
  25. return true // "可以继续上传"
  26. } else {
  27. return false // "切片不完整,废弃"
  28. }
  29. }
  30. func makeFileContent(content []byte, fileName string, FileDir string, contentNumber int) (error, string) {
  31. path := FileDir + fileName + "_" + strconv.Itoa(contentNumber)
  32. f, err := os.Create(path)
  33. if err != nil {
  34. return err, path
  35. } else {
  36. _, err = f.Write(content)
  37. if err != nil {
  38. return err, path
  39. }
  40. }
  41. defer f.Close()
  42. return nil, path
  43. }
  44. func MakeFile(fileName string, FileMd5 string) (error, string) {
  45. rd, err := ioutil.ReadDir(breakpointDir + FileMd5)
  46. if err != nil {
  47. return err, finishDir + fileName
  48. }
  49. _ = os.MkdirAll(finishDir, os.ModePerm)
  50. fd, err := os.OpenFile(finishDir+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
  51. if err != nil {
  52. return err, finishDir + fileName
  53. }
  54. defer fd.Close()
  55. for k := range rd {
  56. content, _ := ioutil.ReadFile(breakpointDir + FileMd5 + "/" + fileName + "_" + strconv.Itoa(k))
  57. _, err = fd.Write(content)
  58. if err != nil {
  59. _ = os.Remove(finishDir + fileName)
  60. return err, finishDir + fileName
  61. }
  62. }
  63. return nil, finishDir + fileName
  64. }
  65. func RemoveChunk(FileMd5 string) error {
  66. err := os.RemoveAll(breakpointDir + FileMd5)
  67. return err
  68. }