Add MultiPartFileHeaderToBase64 function
This commit is contained in:
+38
@@ -1,8 +1,12 @@
|
||||
package ersteller_lib
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -87,3 +91,37 @@ func MoneyCentsToString(money int, currency string, lang Language) string {
|
||||
}
|
||||
return fmt.Sprintf("%s%d.%02d", currency, beforeDecimals, afterDecimals)
|
||||
}
|
||||
|
||||
func MultiPartFileHeaderToBase64(fileHeader *multipart.FileHeader) (string, error) {
|
||||
// Open the uploaded file
|
||||
src, err := fileHeader.Open()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to open uploaded file: %v", err)
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
// Read the file content
|
||||
fileContent, err := io.ReadAll(src)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read file content: %v", err)
|
||||
}
|
||||
|
||||
// Encode the image to base64
|
||||
base64Image := base64.StdEncoding.EncodeToString(fileContent)
|
||||
|
||||
// Determine the MIME type based on file extension
|
||||
filename := strings.ToLower(fileHeader.Filename)
|
||||
var mimeType string
|
||||
if strings.HasSuffix(filename, ".jpg") || strings.HasSuffix(filename, ".jpeg") {
|
||||
mimeType = "image/jpeg"
|
||||
} else if strings.HasSuffix(filename, ".png") {
|
||||
mimeType = "image/png"
|
||||
} else if strings.HasSuffix(filename, ".gif") {
|
||||
mimeType = "image/gif"
|
||||
} else {
|
||||
return "", fmt.Errorf("unsupported image format")
|
||||
}
|
||||
|
||||
// Create the image data URL
|
||||
return fmt.Sprintf("data:%s;base64,%s", mimeType, base64Image), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user