2023-10-05 18:05:30 +00:00
|
|
|
package api
|
2023-10-03 22:09:38 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
)
|
|
|
|
|
|
|
|
func saveFormFile(name string, c echo.Context) (string, error) {
|
|
|
|
file, err := c.FormFile(name)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
src, err := file.Open()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer src.Close()
|
|
|
|
|
2023-10-05 20:42:04 +00:00
|
|
|
tmpDir, err := ensureDir("tmp")
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2023-10-03 22:09:38 +00:00
|
|
|
ext := filepath.Ext(file.Filename)
|
|
|
|
filename := time.Now().Format(time.RFC3339)
|
2023-10-05 20:42:04 +00:00
|
|
|
filename = tmpDir + "/" + sanitizeFilename(filename) + ext
|
2023-10-03 22:09:38 +00:00
|
|
|
|
|
|
|
dst, err := os.Create(filename)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer dst.Close()
|
|
|
|
|
|
|
|
if _, err = io.Copy(dst, src); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return filename, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func sanitizeFilename(filename string) string {
|
|
|
|
invalidChars := []string{`\`, `/`, `:`, `*`, `?`, `"`, `<`, `>`, `|`}
|
|
|
|
for _, char := range invalidChars {
|
|
|
|
filename = strings.ReplaceAll(filename, char, "-")
|
|
|
|
}
|
|
|
|
return filename
|
|
|
|
}
|
2023-10-05 20:42:04 +00:00
|
|
|
|
|
|
|
func ensureDir(dirPath string) (string, error) {
|
|
|
|
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
|
|
|
|
err := os.MkdirAll(dirPath, 0700)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return dirPath, nil
|
|
|
|
}
|