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.

67 lines
2.0 KiB

  1. package upload
  2. import (
  3. "errors"
  4. "gin-vue-admin/global"
  5. "gin-vue-admin/utils"
  6. "go.uber.org/zap"
  7. "io"
  8. "mime/multipart"
  9. "os"
  10. "path"
  11. "strings"
  12. "time"
  13. )
  14. type Local struct{}
  15. // UploadFile 上传文件
  16. func (l Local) UploadFile(file *multipart.FileHeader) (string, string, error) {
  17. // 读取文件后缀
  18. ext := path.Ext(file.Filename)
  19. // 读取文件名并加密
  20. name := strings.TrimSuffix(file.Filename, ext)
  21. name = utils.MD5V([]byte(name))
  22. // 拼接新文件名
  23. filename := name + "_" + time.Now().Format("20060102150405") + ext
  24. // 尝试创建此路径
  25. mkdirErr := os.MkdirAll(global.GVA_CONFIG.Local.Path, os.ModePerm)
  26. if mkdirErr != nil {
  27. global.GVA_LOG.Error("function os.MkdirAll() Filed", zap.Any("err", mkdirErr.Error()))
  28. return "", "", errors.New("function os.MkdirAll() Filed, err:" + mkdirErr.Error())
  29. }
  30. // 拼接路径和文件名
  31. p := global.GVA_CONFIG.Local.Path + "/" + filename
  32. f, openError := file.Open() // 读取文件
  33. if openError != nil {
  34. global.GVA_LOG.Error("function file.Open() Filed", zap.Any("err", openError.Error()))
  35. return "", "", errors.New("function file.Open() Filed, err:" + openError.Error())
  36. }
  37. defer f.Close() // 创建文件 defer 关闭
  38. out, createErr := os.Create(p)
  39. if createErr != nil {
  40. global.GVA_LOG.Error("function os.Create() Filed", zap.Any("err", createErr.Error()))
  41. return "", "", errors.New("function os.Create() Filed, err:" + createErr.Error())
  42. }
  43. defer out.Close() // 创建文件 defer 关闭
  44. _, copyErr := io.Copy(out, f) // 传输(拷贝)文件
  45. if copyErr != nil {
  46. global.GVA_LOG.Error("function io.Copy() Filed", zap.Any("err", copyErr.Error()))
  47. return "", "", errors.New("function io.Copy() Filed, err:" + copyErr.Error())
  48. }
  49. return p, filename, nil
  50. }
  51. // DeleteFile 删除文件
  52. func (l Local) DeleteFile(key string) error {
  53. p := global.GVA_CONFIG.Local.Path + "/" + key
  54. if strings.Contains(p, global.GVA_CONFIG.Local.Path) {
  55. if err := os.Remove(p); err != nil {
  56. return errors.New("本地文件删除失败, err:" + err.Error())
  57. }
  58. }
  59. return nil
  60. }