personal-website/webfilesystem/fileuploading.go

105 lines
2.4 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"
2023-05-07 00:14:30 +00:00
"path"
2023-05-02 00:12:43 +00:00
"go.mongodb.org/mongo-driver/bson/primitive"
)
2023-05-07 00:14:30 +00:00
func (fs *WebFileSystem) UploadFile(realFilepath string, parentPath string) error {
//TODO check is file exists
2023-05-02 00:12:43 +00:00
file, err := os.ReadFile(realFilepath)
if err != nil {
return err
}
splittedPath := fs.SplitPath(realFilepath)
fileName := splittedPath[len(splittedPath)-1]
extension := fs.GetExtension(fileName)
2023-05-07 01:00:22 +00:00
newFile2 := FileHeader{
2023-05-07 00:14:30 +00:00
MongoId: primitive.NewObjectID(),
Name: fileName,
Type: "",
Icon: "",
Data: primitive.NilObjectID,
}
2023-05-07 01:00:22 +00:00
newFileData := BinaryFileData{
2023-05-07 00:14:30 +00:00
MongoId: primitive.NewObjectID(),
Bin: file,
}
filePath := path.Join(parentPath, fileName)
2023-05-02 00:12:43 +00:00
switch extension {
case "jpg":
fallthrough
case "jpeg":
2023-05-07 00:14:30 +00:00
newFile2.Type = "jpeg"
2023-05-07 01:00:22 +00:00
_, _, err := fs.Write(filePath, &newFile2, &newFileData)
2023-05-02 00:12:43 +00:00
return err
case "png":
2023-05-07 00:14:30 +00:00
newFile2.Type = "png"
2023-05-07 01:00:22 +00:00
_, _, err := fs.Write(filePath, &newFile2, &newFileData)
2023-05-07 00:14:30 +00:00
if err != nil {
println(err.Error())
return err
2023-05-02 00:12:43 +00:00
}
2023-05-07 00:14:30 +00:00
return nil
2023-05-02 00:12:43 +00:00
default:
return errors.New("this filetype not allowed")
}
2023-05-04 19:49:22 +00:00
}
2023-05-07 00:14:30 +00:00
2023-05-02 00:12:43 +00:00
// 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)
// }