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.

54 lines
1.4 KiB

  1. package utils
  2. import (
  3. "gin-vue-admin/global"
  4. "go.uber.org/zap"
  5. "io"
  6. "mime/multipart"
  7. "os"
  8. "path"
  9. "strings"
  10. "time"
  11. )
  12. func UploadFileLocal(file *multipart.FileHeader) (err error, localPath string, key string) {
  13. // 读取文件后缀
  14. ext := path.Ext(file.Filename)
  15. // 读取文件名并加密
  16. fileName := strings.TrimSuffix(file.Filename, ext)
  17. fileName = MD5V([]byte(fileName))
  18. // 拼接新文件名
  19. lastName := fileName + "_" + time.Now().Format("20060102150405") + ext
  20. // 读取全局变量的定义路径
  21. savePath := global.GVA_CONFIG.Local.Path
  22. // 尝试创建此路径
  23. err = os.MkdirAll(savePath, os.ModePerm)
  24. if err != nil {
  25. global.GVA_LOG.Error("upload local file fail:", zap.Any("err", err))
  26. return err, "", ""
  27. }
  28. // 拼接路径和文件名
  29. dst := savePath + "/" + lastName
  30. // 下面为上传逻辑
  31. // 打开文件 defer 关闭
  32. src, err := file.Open()
  33. if err != nil {
  34. global.GVA_LOG.Error("upload local file fail:", zap.Any("err", err))
  35. return err, "", ""
  36. }
  37. defer src.Close()
  38. // 创建文件 defer 关闭
  39. out, err := os.Create(dst)
  40. if err != nil {
  41. global.GVA_LOG.Error("upload local file fail:", zap.Any("err", err))
  42. return err, "", ""
  43. }
  44. defer out.Close()
  45. // 传输(拷贝)文件
  46. _, err = io.Copy(out, src)
  47. if err != nil {
  48. global.GVA_LOG.Error("upload local file fail:", zap.Any("err", err))
  49. return err, "", ""
  50. }
  51. return nil, dst, lastName
  52. }