Add MultiPartFileHeaderToBase64 function
This commit is contained in:
+38
@@ -1,8 +1,12 @@
|
|||||||
package ersteller_lib
|
package ersteller_lib
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -87,3 +91,37 @@ func MoneyCentsToString(money int, currency string, lang Language) string {
|
|||||||
}
|
}
|
||||||
return fmt.Sprintf("%s%d.%02d", currency, beforeDecimals, afterDecimals)
|
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