119 lines
2.5 KiB
Go

package sysStorage
import (
"bytes"
"donat-widget/internal/model"
"io"
"mime/multipart"
"os"
"path/filepath"
)
type LocalStorage struct {
basePath string
}
func NewLocalStorage(basePath string) *LocalStorage {
if basePath == "" {
var err error
basePath, err = os.Getwd()
if err != nil {
panic("Failed to get current directory: " + err.Error())
}
}
if err := os.MkdirAll(basePath, os.ModePerm); err != nil {
panic("Failed to create storage directory: " + err.Error())
}
return &LocalStorage{basePath: basePath}
}
func (ls *LocalStorage) Upload(
file *multipart.FileHeader,
filename string,
size int64,
collection string,
) (model.FileID, error) {
// Создаем путь для коллекции, если он не существует
collectionPath := filepath.Join(ls.basePath, collection)
if err := os.MkdirAll(collectionPath, os.ModePerm); err != nil {
return "error", err
}
// Создаем путь для файла
filePath := filepath.Join(collectionPath, filename)
f, err := os.Create(filePath)
if err != nil {
return "error creating", err
}
defer f.Close()
// Открываем исходный файл для чтения
srcFile, err := file.Open()
if err != nil {
return "error opening file", err
}
defer srcFile.Close()
// Копируем содержимое файла
_, err = io.Copy(f, srcFile)
if err != nil {
return "error copy", err
}
// Возвращаем идентификатор файла
return model.FileID(filename), nil
}
func (ls *LocalStorage) Download(
FileID model.FileID,
) ([]byte, error) {
filePath := string(FileID)
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer f.Close()
var fileBuffer bytes.Buffer
_, err = io.Copy(&fileBuffer, f)
if err != nil {
return nil, err
}
return fileBuffer.Bytes(), nil
}
func (ls *LocalStorage) Update(
file *multipart.FileHeader,
fileID model.FileID,
filename string,
size int64,
collection string,
) error {
// Получаем путь для хранения файла
filePath := string(fileID)
// Создаем новый файл
f, err := os.Create(filePath)
if err != nil {
return err
}
defer f.Close()
// Открываем файл из multipart.FileHeader
srcFile, err := file.Open()
if err != nil {
return err
}
defer srcFile.Close()
// Копируем содержимое из исходного файла в новый файл
_, err = io.Copy(f, srcFile)
if err != nil {
return err
}
return nil
}