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.

76 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. err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
  49. //删除切片信息
  50. if err = tx.Delete(&model.ExaSimpleUploader{}, "identifier = ? AND is_done = ?", md5, false).Error; err != nil {
  51. fmt.Println(err)
  52. return err
  53. }
  54. data := model.ExaSimpleUploader{
  55. Identifier: md5,
  56. IsDone: true,
  57. FilePath: finishDir + fileName,
  58. Filename: fileName,
  59. }
  60. // 添加文件信息
  61. if err = tx.Create(&data).Error; err != nil {
  62. fmt.Println(err)
  63. return err
  64. }
  65. return nil
  66. })
  67. err = os.RemoveAll(dir) //清除切片
  68. return err
  69. }