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 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. notFinish := errors.Is(global.GVA_DB.First(&model.ExaSimpleUploader{}, "identifier = ? AND is_done = ?", md5, true).Error, gorm.ErrRecordNotFound)
  28. if !notFinish {
  29. return nil
  30. }
  31. //打开切片文件夹
  32. rd, err := ioutil.ReadDir(dir)
  33. _ = os.MkdirAll(finishDir, os.ModePerm)
  34. //创建目标文件
  35. fd, _ := os.OpenFile(finishDir+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
  36. //将切片文件按照顺序写入
  37. for k := range rd {
  38. content, _ := ioutil.ReadFile(dir + "/" + fileName + strconv.Itoa(k+1))
  39. _, err = fd.Write(content)
  40. if err != nil {
  41. _ = os.Remove(finishDir + fileName)
  42. }
  43. }
  44. //关闭文件
  45. defer fd.Close()
  46. if err != nil {
  47. return err
  48. }
  49. //创建事务
  50. tx := global.GVA_DB.Begin()
  51. //删除切片信息
  52. err = tx.Delete(&model.ExaSimpleUploader{}, "identifier = ? AND is_done = ?", md5, false).Error
  53. // 添加文件信息
  54. if err != nil {
  55. fmt.Println(err)
  56. tx.Rollback()
  57. }
  58. err = tx.Create(&model.ExaSimpleUploader{
  59. Identifier: md5,
  60. IsDone: true,
  61. FilePath: finishDir + fileName,
  62. Filename: fileName,
  63. }).Error
  64. if err != nil {
  65. fmt.Println(err)
  66. tx.Rollback()
  67. }
  68. tx.Commit()
  69. //清除切片
  70. err = os.RemoveAll(dir)
  71. return
  72. }