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.

77 lines
2.0 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. // 保存文件切片路径
  13. func SaveChunk(uploader model.ExaSimpleUploader) (err error) {
  14. return global.GVA_DB.Create(uploader).Error
  15. }
  16. // 检查文件是否已经上传过
  17. func CheckFileMd5(md5 string) (err error, uploads []model.ExaSimpleUploader, isDone bool) {
  18. err = global.GVA_DB.Find(&uploads, "identifier = ? AND is_done = ?", md5, false).Error
  19. isDone = errors.Is(global.GVA_DB.First(&model.ExaSimpleUploader{}, "identifier = ? AND is_done = ?", md5, true).Error, gorm.ErrRecordNotFound)
  20. return err, uploads, !isDone
  21. }
  22. // 合并文件
  23. func MergeFileMd5(md5 string, fileName string) (err error) {
  24. finishDir := "./finish/"
  25. dir := "./chunk/" + md5
  26. //如果文件上传成功 不做后续操作 通知成功即可
  27. if !errors.Is(global.GVA_DB.First(&model.ExaSimpleUploader{}, "identifier = ? AND is_done = ?", md5, true).Error, gorm.ErrRecordNotFound) {
  28. return nil
  29. }
  30. //打开切片文件夹
  31. rd, err := ioutil.ReadDir(dir)
  32. _ = os.MkdirAll(finishDir, os.ModePerm)
  33. //创建目标文件
  34. fd, _ := os.OpenFile(finishDir+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
  35. //将切片文件按照顺序写入
  36. for k := range rd {
  37. content, _ := ioutil.ReadFile(dir + "/" + fileName + strconv.Itoa(k+1))
  38. _, err = fd.Write(content)
  39. if err != nil {
  40. _ = os.Remove(finishDir + fileName)
  41. }
  42. }
  43. //关闭文件
  44. defer fd.Close()
  45. if err != nil {
  46. return err
  47. }
  48. //创建事务
  49. tx := global.GVA_DB.Begin()
  50. //删除切片信息
  51. err = tx.Delete(&model.ExaSimpleUploader{}, "identifier = ? AND is_done = ?", md5, false).Error
  52. // 添加文件信息
  53. if err != nil {
  54. fmt.Println(err)
  55. tx.Rollback()
  56. }
  57. err = tx.Create(&model.ExaSimpleUploader{
  58. Identifier: md5,
  59. IsDone: true,
  60. FilePath: finishDir + fileName,
  61. Filename: fileName,
  62. }).Error
  63. if err != nil {
  64. fmt.Println(err)
  65. tx.Rollback()
  66. }
  67. tx.Commit()
  68. //清除切片
  69. err = os.RemoveAll(dir)
  70. return
  71. }