personal-website/webfilesystem/fileuploading.go

95 lines
2.2 KiB
Go
Raw Normal View History

2023-05-02 00:12:43 +00:00
package webfilesystem
//sudo apt-get install libvips-tools
import (
"errors"
"os"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func (fs *WebFileSystem) UploadFile(realFilepath string, path string) error {
file, err := os.ReadFile(realFilepath)
if err != nil {
return err
}
splittedPath := fs.SplitPath(realFilepath)
fileName := splittedPath[len(splittedPath)-1]
extension := fs.GetExtension(fileName)
switch extension {
case "jpg":
fallthrough
case "jpeg":
newFile := WebFSFile{
MongoId: primitive.NewObjectID(),
Name: fileName,
Type: "jpeg",
Data: file,
Icon: "",
}
err := fs.CreateFile(&newFile, path)
return err
case "png":
newFile := WebFSFile{
MongoId: primitive.NewObjectID(),
Name: fileName,
Type: "png",
Data: file,
}
err := fs.CreateFile(&newFile, path)
return err
default:
return errors.New("this filetype not allowed")
}
}
// func (fs *WebFileSystem) CreateMiniatures(parentDir string, file string) error {
// src, err := imaging.Open(path.Join(parentDir, file))
// if err != nil {
// // log.Fatalf("failed to open image: %v", err)
// return err
// }
// // Resize the cropped image to width = 200px preserving the aspect ratio.
// src = imaging.Resize(src, 32, 0, imaging.Lanczos)
// // Save the resulting image as JPEG.
// splittedFileName := strings.Split(file, ".")
// err = imaging.Save(src, path.Join(parentDir, splittedFileName[0]+"_32px."+splittedFileName[1]))
// if err != nil {
// // log.Fatalf("failed to save image: %v", err)
// return err
// }
// data, err := os.ReadFile(path.Join(parentDir, file))
// if err != nil {
// return err
// }
// min32Data, err := os.ReadFile(path.Join(parentDir, splittedFileName[0]+"_32px."+splittedFileName[1]))
// if err != nil {
// return err
// }
// imgData := wde.Img{
// Header: "",
// Data: data,
// Miniature32: min32Data,
// }
// newFile := WebFSFile{
// MongoId: primitive.NewObjectID(),
// Name: file,
// Type: "picture",
// Data: imgData,
// Icon: "",
// }
// fs.CreateFile(&newFile, "/home/user/")
// return nil
// }
// func toBase64(b []byte) string {
// return base64.StdEncoding.EncodeToString(b)
// }