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.

94 lines
2.5 KiB

  1. package service
  2. import (
  3. "errors"
  4. "fmt"
  5. "gin-vue-admin/global"
  6. "gin-vue-admin/model"
  7. "gorm.io/gorm"
  8. "io/ioutil"
  9. "os"
  10. "strconv"
  11. )
  12. //@author: [piexlmax](https://github.com/piexlmax)
  13. //@function: SaveChunk
  14. //@description: 保存文件切片路径
  15. //@param: uploader model.ExaSimpleUploader
  16. //@return: err error
  17. func SaveChunk(uploader model.ExaSimpleUploader) (err error) {
  18. return global.GVA_DB.Create(uploader).Error
  19. }
  20. //@author: [piexlmax](https://github.com/piexlmax)
  21. //@function: CheckFileMd5
  22. //@description: 检查文件是否已经上传过
  23. //@param: md5 string
  24. //@return: err error, uploads []model.ExaSimpleUploader, isDone bool
  25. func CheckFileMd5(md5 string) (err error, uploads []model.ExaSimpleUploader, isDone bool) {
  26. err = global.GVA_DB.Find(&uploads, "identifier = ? AND is_done = ?", md5, false).Error
  27. isDone = errors.Is(global.GVA_DB.First(&model.ExaSimpleUploader{}, "identifier = ? AND is_done = ?", md5, true).Error, gorm.ErrRecordNotFound)
  28. return err, uploads, !isDone
  29. }
  30. //@author: [piexlmax](https://github.com/piexlmax)
  31. //@function: MergeFileMd5
  32. //@description: 合并文件
  33. //@param: md5 string, fileName string
  34. //@return: err error
  35. func MergeFileMd5(md5 string, fileName string) (err error) {
  36. finishDir := "./finish/"
  37. dir := "./chunk/" + md5
  38. // 如果文件上传成功 不做后续操作 通知成功即可
  39. if !errors.Is(global.GVA_DB.First(&model.ExaSimpleUploader{}, "identifier = ? AND is_done = ?", md5, true).Error, gorm.ErrRecordNotFound) {
  40. return nil
  41. }
  42. // 打开切片文件夹
  43. rd, err := ioutil.ReadDir(dir)
  44. _ = os.MkdirAll(finishDir, os.ModePerm)
  45. // 创建目标文件
  46. fd, err := os.OpenFile(finishDir+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
  47. if err != nil {
  48. return
  49. }
  50. // 关闭文件
  51. defer fd.Close()
  52. // 将切片文件按照顺序写入
  53. for k := range rd {
  54. content, _ := ioutil.ReadFile(dir + "/" + fileName + strconv.Itoa(k+1))
  55. _, err = fd.Write(content)
  56. if err != nil {
  57. _ = os.Remove(finishDir + fileName)
  58. }
  59. }
  60. if err != nil {
  61. return err
  62. }
  63. err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
  64. // 删除切片信息
  65. if err = tx.Delete(&model.ExaSimpleUploader{}, "identifier = ? AND is_done = ?", md5, false).Error; err != nil {
  66. fmt.Println(err)
  67. return err
  68. }
  69. data := model.ExaSimpleUploader{
  70. Identifier: md5,
  71. IsDone: true,
  72. FilePath: finishDir + fileName,
  73. Filename: fileName,
  74. }
  75. // 添加文件信息
  76. if err = tx.Create(&data).Error; err != nil {
  77. fmt.Println(err)
  78. return err
  79. }
  80. return nil
  81. })
  82. err = os.RemoveAll(dir) // 清除切片
  83. return err
  84. }