liuchangshun 1 ano atrás
pai
commit
97835670b3
1 arquivos alterados com 36 adições e 0 exclusões
  1. 36 0
      lxCommon/file.go

+ 36 - 0
lxCommon/file.go

@@ -1,6 +1,7 @@
 package lxCommon
 
 import (
+	"encoding/base64"
 	"fmt"
 	"io"
 	"io/ioutil"
@@ -97,3 +98,38 @@ func PathIsExists(path string) (bool, error) {
 	}
 	return false, err
 }
+
+func FileToBase64(filePath string) (imgBase64str string, err error) {
+	//file, err := c.FormFile("file")
+	//if err != nil {
+	//	common.SendErrJSON("文件不存在", c)
+	//	return
+	//}
+	//imgFile, err := file.Open()
+	imgFile, err := os.Open(filePath)
+	if err != nil {
+		return
+	}
+	defer imgFile.Close()
+	buf, err := io.ReadAll(imgFile)
+	if err != nil {
+		return
+	}
+	imgBase64str = base64.StdEncoding.EncodeToString(buf)
+	return
+}
+
+func Base64ToFile(imgBase64str string, name string) (err error) {
+	data, err := base64.StdEncoding.DecodeString(imgBase64str)
+	if err != nil {
+		fmt.Println("base64 decode error:", err)
+		return
+	}
+	// 将解码后的字符串写入文件
+	err = os.WriteFile(name, data, 0644)
+	if err != nil {
+		fmt.Println("write file error:", err)
+		return
+	}
+	return
+}