43 lines
1.0 KiB
Go
43 lines
1.0 KiB
Go
package fileutils
|
|
|
|
import (
|
|
"mime/multipart"
|
|
"path/filepath"
|
|
"strconv"
|
|
|
|
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
|
|
"git.artlef.fr/PersonalLibraryManager/internal/model"
|
|
)
|
|
|
|
func SaveStaticFile(ac *appcontext.AppContext, file *multipart.FileHeader) (model.StaticFile, error) {
|
|
filename := file.Filename
|
|
filepath := computePathFromName(ac, filename)
|
|
err := ac.C.SaveUploadedFile(file, ac.Config.ImageFolderPath+"/"+filepath)
|
|
if err != nil {
|
|
return model.StaticFile{}, err
|
|
}
|
|
staticFile := model.StaticFile{
|
|
Name: filename,
|
|
Path: filepath,
|
|
}
|
|
ac.Db.Save(&staticFile)
|
|
return staticFile, nil
|
|
}
|
|
|
|
func computePathFromName(ac *appcontext.AppContext, filename string) string {
|
|
var existingFiles []model.StaticFile
|
|
ac.Db.Where("name = ?", filename).Find(&existingFiles)
|
|
l := len(existingFiles)
|
|
if l == 0 {
|
|
return filename
|
|
} else {
|
|
extension := filepath.Ext(filename)
|
|
basename := filename[:len(filename)-len(extension)]
|
|
return basename + "-" + strconv.Itoa(l) + extension
|
|
}
|
|
}
|
|
|
|
func GetWsLinkPrefix() string {
|
|
return "/bookcover/"
|
|
}
|