draincloud-core/internal/app/upload_file.go

82 lines
1.8 KiB
Go
Raw Normal View History

2024-11-23 08:52:06 +00:00
package app
import (
2024-11-29 05:23:56 +00:00
"fmt"
2024-11-23 08:52:06 +00:00
"io"
"log/slog"
2024-11-29 05:23:56 +00:00
"strings"
2024-11-23 08:52:06 +00:00
filesengine "git.optclblast.xyz/draincloud/draincloud-core/internal/files_engine"
"git.optclblast.xyz/draincloud/draincloud-core/internal/logger"
2024-11-29 05:23:56 +00:00
"git.optclblast.xyz/draincloud/draincloud-core/internal/reqcontext"
2024-11-23 08:52:06 +00:00
"github.com/davecgh/go-spew/spew"
"github.com/gin-gonic/gin"
2024-12-16 05:08:37 +00:00
"github.com/google/uuid"
2024-11-23 08:52:06 +00:00
)
const (
maxFileSize = 10 << 30
)
func (d *DrainCloud) UploadFile(ctx *gin.Context) {
if err := ctx.Request.ParseMultipartForm(maxFileSize); err != nil {
logger.Error(ctx, "uploadFile handler error", logger.Err(err))
writeError(ctx, err)
return
}
2024-11-29 05:23:56 +00:00
userID, err := reqcontext.GetUserID(ctx)
if err != nil {
writeError(ctx, ErrorAccessDenied)
return
}
if err := d.uploadFile(ctx, userID); err != nil {
2024-11-23 08:52:06 +00:00
logger.Error(ctx, "uploadFile handle", logger.Err(err))
writeError(ctx, err)
return
}
}
2024-12-16 05:08:37 +00:00
func (d *DrainCloud) uploadFile(ctx *gin.Context, userID uuid.UUID) error {
2024-11-23 08:52:06 +00:00
title := ctx.PostForm("file")
logger.Info(ctx, "uploadFile", slog.Any("postForm data", spew.Sdump(title)))
file, header, err := ctx.Request.FormFile("file")
if err != nil {
return err
}
logger.Info(ctx, "uploadFile", slog.Any("header", spew.Sdump(header)))
data, err := io.ReadAll(file)
if err != nil {
return err
}
2024-11-29 05:23:56 +00:00
ext := parseExtension(header.Filename)
id, err := d.filesEngine.SaveFile(ctx, filesengine.File{
Name: header.Filename,
UserID: userID,
Data: data,
Ext: ext,
Size: int64(len(data)),
Type: "", // че такое type?
2024-11-23 08:52:06 +00:00
})
2024-11-29 05:23:56 +00:00
if err != nil {
return fmt.Errorf("failed to save file: %w", err)
}
logger.Debug(ctx, "new file id", "id", id)
2024-11-23 08:52:06 +00:00
return nil
}
2024-11-29 05:23:56 +00:00
2024-12-14 07:42:59 +00:00
func parseExtension(filename string) string {
2024-11-29 05:23:56 +00:00
parts := strings.Split(filename, ".")
if len(parts) == 0 {
2024-12-14 07:42:59 +00:00
return ""
2024-11-29 05:23:56 +00:00
}
2024-12-14 07:42:59 +00:00
return parts[len(parts)-1]
2024-11-29 05:23:56 +00:00
}