base64image.go 951 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package utils
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "file_upload/backend/global"
  6. "file_upload/backend/simple_zap"
  7. "os"
  8. "strings"
  9. )
  10. func ParseBase64ImageString(input, name string) error {
  11. parts := strings.Split(input, ",")
  12. if len(parts) < 2 {
  13. panic("Invalid Base64 image string")
  14. }
  15. contentTypePart := strings.TrimSpace(parts[0])
  16. contentTypeParts := strings.Split(contentTypePart, ";")
  17. _ = strings.TrimSpace(contentTypeParts[0])
  18. data := parts[1]
  19. decodeString, err := base64.StdEncoding.DecodeString(data)
  20. if err != nil {
  21. return err
  22. }
  23. optputpath := global.DownloadSetting.Path + "/" + name + ".png"
  24. create, err := os.Create(optputpath)
  25. if err != nil {
  26. simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "创建文件失败")
  27. return err
  28. }
  29. defer create.Close()
  30. _, err = create.Write(decodeString)
  31. if err != nil {
  32. simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "写入文件失败")
  33. return err
  34. }
  35. return err
  36. }