50 lines
863 B
Go
50 lines
863 B
Go
|
package service
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"mime/multipart"
|
||
|
|
||
|
"github.com/google/uuid"
|
||
|
"gitrepo.ru/neonxp/nquest/pkg/models"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
type File struct {
|
||
|
DB *gorm.DB
|
||
|
}
|
||
|
|
||
|
func NewFile(db *gorm.DB) *File {
|
||
|
return &File{
|
||
|
DB: db,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (u *File) Upload(
|
||
|
ctx context.Context,
|
||
|
filename string,
|
||
|
contentType string,
|
||
|
size int,
|
||
|
r multipart.File,
|
||
|
) (uuid.UUID, error) {
|
||
|
buf := make([]byte, size)
|
||
|
if _, err := r.Read(buf); err != nil {
|
||
|
return uuid.UUID{}, err
|
||
|
}
|
||
|
|
||
|
file := &models.File{
|
||
|
Model: models.Model{ID: uuid.New()},
|
||
|
Filename: filename,
|
||
|
ContentType: contentType,
|
||
|
Size: size,
|
||
|
Body: buf,
|
||
|
}
|
||
|
|
||
|
return file.ID, u.DB.WithContext(ctx).Create(file).Error
|
||
|
}
|
||
|
|
||
|
func (u *File) GetFile(ctx context.Context, uid uuid.UUID) (*models.File, error) {
|
||
|
f := new(models.File)
|
||
|
|
||
|
return f, u.DB.WithContext(ctx).First(f, uid).Error
|
||
|
}
|